id chat_gpt_response question badsmell_base bad_smell_gpt found_any valid_bad_smell bad_smell_in_base bad_smell_not_in_the_base bad_smell_not_found index index_base url_github nr_question id_source_code id_base
2380     { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); }
feature envy long method, data class t t f long method, data class feature envy 0 14337 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 1 2380 14337
2385  { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } }
blob long method, blob, data class t t t long method, data class   0 14347 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 1 2385 14347
1197    { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; }
long method long method, data class t t t  data class   0 10271 https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 1 1197 10271
5722   YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } }
long method  Long method2 Data class3 Feature envy t f t     0 12971 https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 1 5722 12971
1903 {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } }
blob data class t t f data class blob 0 12365 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 1 1903 12365
2100   YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inconsistent indentation 5. Duplicate code 6. Inconsistent naming convention I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; }
long method  Long method2 Feature envy3 Data class4 Inconsistent indentation5 Duplicate code6 Inconsistent naming convention t f t     0 13158 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 2 2100 13158
664 { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } }
blob blob, data class, long method t t t  data class, long method   0 6459 https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 1 664 6459
868 { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node
feature envy long method, data class t t f long method, data class feature envy 0 7947 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 1 868 7947
1827 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } }
blob Data Class, Long Method t f f Data Class, Long Method blob 0 12115 https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 1 1827 12115
906 { "output": "YES, I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 8195 https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 1 906 8195
436 {"answer":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JpegRewriter extends BinaryFileParser { private static final ByteOrder JPEG_BYTE_ORDER = ByteOrder.BIG_ENDIAN; private static final SegmentFilter EXIF_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isExifSegment(); } }; private static final SegmentFilter XMP_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isXmpSegment(); } }; private static final SegmentFilter PHOTOSHOP_APP13_SEGMENT_FILTER = new SegmentFilter() { @Override public boolean filter(final JFIFPieceSegment segment) { return segment.isPhotoshopApp13Segment(); } }; /** * Constructor. to guess whether a file contains an image based on its file * extension. */ public JpegRewriter() { setByteOrder(JPEG_BYTE_ORDER); } protected static class JFIFPieces { public final List pieces; public final List segmentPieces; public JFIFPieces(final List pieces, final List segmentPieces) { this.pieces = pieces; this.segmentPieces = segmentPieces; } } protected abstract static class JFIFPiece { protected abstract void write(OutputStream os) throws IOException; @Override public String toString() { return "[" + this.getClass().getName() + "]"; } } protected static class JFIFPieceSegment extends JFIFPiece { public final int marker; private final byte[] markerBytes; private final byte[] segmentLengthBytes; private final byte[] segmentData; public JFIFPieceSegment(final int marker, final byte[] segmentData) { this(marker, ByteConversions.toBytes((short) marker, JPEG_BYTE_ORDER), ByteConversions.toBytes((short) (segmentData.length + 2), JPEG_BYTE_ORDER), segmentData); } JFIFPieceSegment(final int marker, final byte[] markerBytes, final byte[] segmentLengthBytes, final byte[] segmentData) { this.marker = marker; this.markerBytes = markerBytes; this.segmentLengthBytes = segmentLengthBytes; this.segmentData = segmentData; // TODO clone? } @Override public String toString() { return "[" + this.getClass().getName() + " (0x" + Integer.toHexString(marker) + ")]"; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(segmentLengthBytes); os.write(segmentData); } public boolean isApp1Segment() { return marker == JpegConstants.JPEG_APP1_MARKER; } public boolean isAppSegment() { return marker >= JpegConstants.JPEG_APP0_MARKER && marker <= JpegConstants.JPEG_APP15_MARKER; } public boolean isExifSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.EXIF_IDENTIFIER_CODE)) { return false; } return true; } public boolean isPhotoshopApp13Segment() { if (marker != JpegConstants.JPEG_APP13_MARKER) { return false; } if (!new IptcParser().isPhotoshopJpegSegment(segmentData)) { return false; } return true; } public boolean isXmpSegment() { if (marker != JpegConstants.JPEG_APP1_MARKER) { return false; } if (!startsWith(segmentData, JpegConstants.XMP_IDENTIFIER)) { return false; } return true; } public byte[] getSegmentData() { return segmentData; // TODO clone? } } static class JFIFPieceImageData extends JFIFPiece { private final byte[] markerBytes; private final byte[] imageData; JFIFPieceImageData(final byte[] markerBytes, final byte[] imageData) { super(); this.markerBytes = markerBytes; this.imageData = imageData; } @Override protected void write(final OutputStream os) throws IOException { os.write(markerBytes); os.write(imageData); } } protected JFIFPieces analyzeJFIF(final ByteSource byteSource) throws ImageReadException, IOException { final List pieces = new ArrayList<>(); final List segmentPieces = new ArrayList<>(); final JpegUtils.Visitor visitor = new JpegUtils.Visitor() { // return false to exit before reading image data. @Override public boolean beginSOS() { return true; } @Override public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) { pieces.add(new JFIFPieceImageData(markerBytes, imageData)); } // return false to exit traversal. @Override public boolean visitSegment(final int marker, final byte[] markerBytes, final int segmentLength, final byte[] segmentLengthBytes, final byte[] segmentData) throws ImageReadException, IOException { final JFIFPiece piece = new JFIFPieceSegment(marker, markerBytes, segmentLengthBytes, segmentData); pieces.add(piece); segmentPieces.add(piece); return true; } }; new JpegUtils().traverseJFIF(byteSource, visitor); return new JFIFPieces(pieces, segmentPieces); } private interface SegmentFilter { boolean filter(JFIFPieceSegment segment); } protected List removeXmpSegments(final List segments) { return filterSegments(segments, XMP_SEGMENT_FILTER); } protected List removePhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER); } protected List findPhotoshopApp13Segments( final List segments) { return filterSegments(segments, PHOTOSHOP_APP13_SEGMENT_FILTER, true); } protected List removeExifSegments(final List segments) { return filterSegments(segments, EXIF_SEGMENT_FILTER); } protected List filterSegments(final List segments, final SegmentFilter filter) { return filterSegments(segments, filter, false); } protected List filterSegments(final List segments, final SegmentFilter filter, final boolean reverse) { final List result = new ArrayList<>(); for (final T piece : segments) { if (piece instanceof JFIFPieceSegment) { if (filter.filter((JFIFPieceSegment) piece) ^ !reverse) { result.add(piece); } } else if (!reverse) { result.add(piece); } } return result; } protected List insertBeforeFirstAppSegments( final List segments, final List newSegments) throws ImageWriteException { int firstAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { if (firstAppIndex == -1) { firstAppIndex = i; } } } final List result = new ArrayList(segments); if (firstAppIndex == -1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(firstAppIndex, newSegments); return result; } protected List insertAfterLastAppSegments( final List segments, final List newSegments) throws ImageWriteException { int lastAppIndex = -1; for (int i = 0; i < segments.size(); i++) { final JFIFPiece piece = segments.get(i); if (!(piece instanceof JFIFPieceSegment)) { continue; } final JFIFPieceSegment segment = (JFIFPieceSegment) piece; if (segment.isAppSegment()) { lastAppIndex = i; } } final List result = new ArrayList(segments); if (lastAppIndex == -1) { if (segments.size() < 1) { throw new ImageWriteException("JPEG file has no APP segments."); } result.addAll(1, newSegments); } else { result.addAll(lastAppIndex + 1, newSegments); } return result; } protected void writeSegments(final OutputStream outputStream, final List segments) throws IOException { try (DataOutputStream os = new DataOutputStream(outputStream)) { JpegConstants.SOI.writeTo(os); for (final JFIFPiece piece : segments) { piece.write(os); } } } // private void writeSegment(OutputStream os, JFIFPieceSegment piece) // throws ImageWriteException, IOException // { // byte markerBytes[] = convertShortToByteArray(JPEG_APP1_MARKER, // JPEG_BYTE_ORDER); // if (piece.segmentData.length > 0xffff) // throw new JpegSegmentOverflowException("Jpeg segment is too long: " // + piece.segmentData.length); // int segmentLength = piece.segmentData.length + 2; // byte segmentLengthBytes[] = convertShortToByteArray(segmentLength, // JPEG_BYTE_ORDER); // // os.write(markerBytes); // os.write(segmentLengthBytes); // os.write(piece.segmentData); // } public static class JpegSegmentOverflowException extends ImageWriteException { private static final long serialVersionUID = -1062145751550646846L; public JpegSegmentOverflowException(final String message) { super(message); } } }
blob data class, long method t t f data class, long method blob 0 4290 https://github.com/apache/commons-imaging/blob/fa7c16f434061d441d1c0d9dbcfd0f4c3092c880/src/main/java/org/apache/commons/imaging/formats/jpeg/xmp/JpegRewriter.java/#L40-L353 1 436 4290
2013 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); }
long method long method, data class t t t  data class   0 12755 https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 1 2013 12755
2615 { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 15047 https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 1 2615 15047
1049       { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); }
feature envy long method, data class t t f long method, data class feature envy 0 9463 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 1 1049 9463
594 {"message": "YES, I found bad smells", "detected_bad_smells": ["1. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class DirectExecutorService implements ExecutorService { static final DirectExecutorService INSTANCE = new DirectExecutorService(); private boolean isShutdown = false; @Override public void shutdown() { isShutdown = true; } @Override @Nonnull public List shutdownNow() { isShutdown = true; return Collections.emptyList(); } @Override public boolean isShutdown() { return isShutdown; } @Override public boolean isTerminated() { return isShutdown; } @Override public boolean awaitTermination(long timeout, @Nonnull TimeUnit unit) { return isShutdown; } @Override @Nonnull public Future submit(@Nonnull Callable task) { try { T result = task.call(); return new CompletedFuture<>(result, null); } catch (Exception e) { return new CompletedFuture<>(null, e); } } @Override @Nonnull public Future submit(@Nonnull Runnable task, T result) { task.run(); return new CompletedFuture<>(result, null); } @Override @Nonnull public Future submit(@Nonnull Runnable task) { task.run(); return new CompletedFuture<>(null, null); } @Override @Nonnull public List> invokeAll(@Nonnull Collection> tasks) { ArrayList> result = new ArrayList<>(); for (Callable task : tasks) { try { result.add(new CompletedFuture<>(task.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } return result; } @Override @Nonnull public List> invokeAll( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) { long end = System.currentTimeMillis() + unit.toMillis(timeout); Iterator> iterator = tasks.iterator(); ArrayList> result = new ArrayList<>(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { result.add(new CompletedFuture<>(callable.call(), null)); } catch (Exception e) { result.add(new CompletedFuture<>(null, e)); } } while (iterator.hasNext()) { iterator.next(); result.add(new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean isDone() { return false; } @Override public T get() { throw new CancellationException("Task has been cancelled."); } @Override public T get(long timeout, @Nonnull TimeUnit unit) { throw new CancellationException("Task has been cancelled."); } }); } return result; } @Override @Nonnull public T invokeAny(@Nonnull Collection> tasks) throws ExecutionException { Exception exception = null; for (Callable task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); } @Override public T invokeAny( @Nonnull Collection> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis(timeout); Exception exception = null; Iterator> iterator = tasks.iterator(); while (end > System.currentTimeMillis() && iterator.hasNext()) { Callable callable = iterator.next(); try { return callable.call(); } catch (Exception e) { // ignore exception and try next exception = e; } } if (iterator.hasNext()) { throw new TimeoutException("Could not finish execution of tasks within time."); } else { throw new ExecutionException("No tasks finished successfully.", exception); } } @Override public void execute(@Nonnull Runnable command) { command.run(); } static class CompletedFuture implements Future { private final V value; private final Exception exception; CompletedFuture(V value, Exception exception) { this.value = value; this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public V get() throws ExecutionException { if (exception != null) { throw new ExecutionException(exception); } else { return value; } } @Override public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException { return get(); } } }
blob 1. data class t t f 1. data class blob 0 5924 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/DirectExecutorService.java/#L37-L252 1 594 5924
833 { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } }
blob long method, data class t t f long method, data class blob 0 7743 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 1 833 7743
3750      { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, PhoenixIndexFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } }
feature envy data class t t f data class feature envy 0 9355 https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/write/IndexWriter.java/#L87-L100 1 3750 9355
2234 {"response": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } }
blob data class t t f data class blob 0 13604 https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 1 2234 13604
477 {"output":"YES, I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } }
blob long method, data class t t f long method, data class blob 0 4591 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 1 477 4591
1756   YES I found bad smells The bad smells are: 1. Long method 2. Data class 3. Brain method 4. Feature envy 5. Large class I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } }
blob  Long method2 Data class3 Brain method4 Feature envy5 Large class t f f . Long method2. Data class3. Brain method4. Feature envy5. Large class blob 0 11876 https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 2 1756 11876
537      { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 5493 https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 1 537 5493
3479 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } }
long method long method, data class t t t  data class   0 7119 https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 1 3479 7119
1951  {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; }
long method data class, long method t t f data class long method 0 12534 https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 1 1951 12534
276      { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } }
long method long method, data class t t t  data class   0 2964 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 1 276 2964
905 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SequenceFileReader extends AbstractFileReader { public static final String[] defaultFields = { "key", "value" }; public static final String BUFFER_SIZE = "hdfsspout.reader.buffer.bytes"; private static final Logger LOG = LoggerFactory .getLogger(SequenceFileReader.class); private static final int DEFAULT_BUFF_SIZE = 4096; private final SequenceFile.Reader reader; private final SequenceFileReader.Offset offset; private final Key key; private final Value value; public SequenceFileReader(FileSystem fs, Path file, Map conf) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); this.offset = new SequenceFileReader.Offset(0, 0, 0); } public SequenceFileReader(FileSystem fs, Path file, Map conf, String offset) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.offset = new SequenceFileReader.Offset(offset); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); skipToOffset(this.reader, this.offset, this.key); } private static void skipToOffset(SequenceFile.Reader reader, Offset offset, K key) throws IOException { reader.sync(offset.lastSyncPoint); for (int i = 0; i < offset.recordsSinceLastSync; ++i) { reader.next(key); } } public List next() throws IOException, ParseException { if (reader.next(key, value)) { ArrayList result = new ArrayList(2); Collections.addAll(result, key, value); offset.increment(reader.syncSeen(), reader.getPosition()); return result; } return null; } @Override public void close() { try { reader.close(); } catch (IOException e) { LOG.warn("Ignoring error when closing file " + getFilePath(), e); } } public Offset getFileOffset() { return offset; } public static class Offset implements FileOffset { public long lastSyncPoint; public long recordsSinceLastSync; public long currentRecord; private long currRecordEndOffset; private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if (offset == null) { throw new IllegalArgumentException("offset cannot be null"); } if (offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if (rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord + 1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if (currentRecord < rhs.currentRecord) { return -1; } if (currentRecord == rhs.currentRecord) { return 0; } return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Offset)) { return false; } Offset offset = (Offset) o; return currentRecord == offset.currentRecord; } @Override public int hashCode() { return (int) (currentRecord ^ (currentRecord >>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if (!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class
blob long method, data class t t f long method, data class blob 0 8183 https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/SequenceFileReader.java/#L28-L209 1 905 8183
3130 {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } }
blob data class, long method t t f data class, long method blob 0 4236 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 1 3130 4236
2338 {"response": "YES I found bad smells", "detectedBadSmells": [{"1": "Long Method"}, {"2": "Data Class"}]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PasswordPolicyDetailsPage implements IDetailsPage { /** The associated Master Details Block */ private PasswordPoliciesMasterDetailsBlock masterDetailsBlock; /** The Managed Form */ private IManagedForm mform; /** The input password policy */ private PasswordPolicyBean passwordPolicy; // UI Widgets private Button enabledCheckbox; private Text idText; private Text descriptionText; private ComboViewer checkQualityComboViewer; private Text validatorText; private Button minimumLengthCheckbox; private Text minimumLengthText; private Button maximumLengthCheckbox; private Text maximumLengthText; private Text minimumAgeText; private Text maximumAgeText; private Button expireWarningCheckbox; private Text expireWarningText; private Button graceAuthenticationLimitCheckbox; private Text graceAuthenticationLimitText; private Button graceExpireCheckbox; private Text graceExpireText; private Button mustChangeCheckbox; private Button allowUserChangeCheckbox; private Button safeModifyCheckbox; private Button lockoutCheckbox; private Text lockoutDurationText; private Text maxFailureText; private Text failureCountIntervalText; private Button inHistoryCheckbox; private Text inHistoryText; private Button maxIdleCheckbox; private Text maxIdleText; private Text minimumDelayText; private Text maximumDelayText; // Listeners /** The Text Modify Listener */ private ModifyListener textModifyListener = new ModifyListener() { public void modifyText( ModifyEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The button Selection Listener */ private SelectionListener buttonSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; /** The viewer Selection Changed Listener */ private ISelectionChangedListener viewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { commit( true ); masterDetailsBlock.setEditorDirty(); } }; private VerifyListener integerVerifyListener = new VerifyListener() { public void verifyText( VerifyEvent e ) { if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$ { e.doit = false; } } }; private ISelectionChangedListener checkQualityComboViewerSelectionChangedListener = new ISelectionChangedListener() { public void selectionChanged( SelectionChangedEvent event ) { StructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); if ( checkQuality == CheckQuality.DISABLED ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { int minimumLength = 0; int maximumLength = 0; try { minimumLength = Integer.parseInt( minimumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } try { maximumLength = Integer.parseInt( maximumLengthText.getText() ); } catch ( NumberFormatException e ) { // Nothing to do. } minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } } } }; private SelectionListener minimumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { minimumLengthText.setEnabled( minimumLengthCheckbox.getSelection() ); } }; private SelectionListener maximumLengthCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maximumLengthText.setEnabled( maximumLengthCheckbox.getSelection() ); } }; private SelectionListener expireWarningCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { expireWarningText.setEnabled( expireWarningCheckbox.getSelection() ); } }; private SelectionListener graceAuthenticationLimitCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceAuthenticationLimitText.setEnabled( graceAuthenticationLimitCheckbox.getSelection() ); } }; private SelectionListener graceExpireCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { graceExpireText.setEnabled( graceExpireCheckbox.getSelection() ); } }; private SelectionListener maxIdleCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { maxIdleText.setEnabled( maxIdleCheckbox.getSelection() ); } }; private SelectionListener inHistoryCheckboxSelectionListener = new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { inHistoryText.setEnabled( inHistoryCheckbox.getSelection() ); } }; /** * Creates a new instance of PartitionDetailsPage. * * @param pmdb * the associated Master Details Block */ public PasswordPolicyDetailsPage( PasswordPoliciesMasterDetailsBlock pmdb ) { masterDetailsBlock = pmdb; } /** * {@inheritDoc} */ public void createContents( Composite parent ) { FormToolkit toolkit = mform.getToolkit(); TableWrapLayout layout = new TableWrapLayout(); layout.topMargin = 5; layout.leftMargin = 5; layout.rightMargin = 2; layout.bottomMargin = 2; parent.setLayout( layout ); // Depending on if the PP is enabled or disabled, we will // expose the configuration createDetailsSection( toolkit, parent ); createQualitySection( toolkit, parent ); createExpirationSection( toolkit, parent ); createOptionsSection( toolkit, parent ); createLockoutSection( toolkit, parent ); } /** * Creates the Details Section * * @param parent * the parent composite * @param toolkit * the toolkit to use */ private void createDetailsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Password Policy Details" ); section.setDescription( "Set the properties of the password policy." ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite client = toolkit.createComposite( section ); toolkit.paintBordersFor( client ); GridLayout glayout = new GridLayout( 2, false ); client.setLayout( glayout ); section.setClient( client ); // Enabled Checkbox enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK ); enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) ); // ID Text toolkit.createLabel( client, "ID:" ); idText = toolkit.createText( client, "" ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // Description Text toolkit.createLabel( client, "Description:" ); descriptionText = toolkit.createText( client, "" ); descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } /** * Creates the Quality section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createQualitySection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Quality" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Check Quality (pwdCheckQuality) toolkit.createLabel( composite, "Check Quality:" ); checkQualityComboViewer = new ComboViewer( composite ); checkQualityComboViewer.setContentProvider( new ArrayContentProvider() ); checkQualityComboViewer.setInput( new CheckQuality[] { CheckQuality.DISABLED, CheckQuality.RELAXED, CheckQuality.STRICT } ); checkQualityComboViewer.getControl().setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Validator toolkit.createLabel( composite, "Validator:" ); validatorText = toolkit.createText( composite, "" ); validatorText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum Length (pwdMinLength) minimumLengthCheckbox = toolkit.createButton( composite, "Enable Mimimum Length", SWT.CHECK ); minimumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite mimimumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); minimumLengthText = toolkit.createText( mimimumLengthRadioIndentComposite, "" ); minimumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Length (pwdMaxLength) maximumLengthCheckbox = toolkit.createButton( composite, "Enable Maximum Length", SWT.CHECK ); maximumLengthCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite maximumLengthRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of characters:" ); maximumLengthText = toolkit.createText( maximumLengthRadioIndentComposite, "" ); maximumLengthText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Expiration section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createExpirationSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Expiration" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Minimum Age (pwdMinAge) toolkit.createLabel( composite, "Mimimum Age (seconds):" ); minimumAgeText = toolkit.createText( composite, "" ); minimumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Age (pwdMaxAge) toolkit.createLabel( composite, "Maximum Age (seconds):" ); maximumAgeText = toolkit.createText( composite, "" ); maximumAgeText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Expire Warning (pwdExpireWarning) expireWarningCheckbox = toolkit.createButton( composite, "Enable Expire Warning", SWT.CHECK ); expireWarningCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite expireWarningRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of seconds:" ); expireWarningText = toolkit.createText( expireWarningRadioIndentComposite, "" ); expireWarningText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Authentication Limit (pwdGraceAuthNLimit) graceAuthenticationLimitCheckbox = toolkit.createButton( composite, "Enable Grace Authentication Limit", SWT.CHECK ); graceAuthenticationLimitCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceAuthenticationLimitRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Number of times:" ); graceAuthenticationLimitText = toolkit.createText( graceAuthenticationLimitRadioIndentComposite, "" ); graceAuthenticationLimitText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Grace Expire (pwdGraceExpire) graceExpireCheckbox = toolkit.createButton( composite, "Enable Grace Expire", SWT.CHECK ); graceExpireCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite graceExpireRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); graceExpireText = toolkit.createText( graceExpireRadioIndentComposite, "" ); graceExpireText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates the Options section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createOptionsSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Options" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Must Change (pwdMustChange) mustChangeCheckbox = toolkit.createButton( composite, "Enable Must Change", SWT.CHECK ); mustChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Allow User Change (pwdAllowUserChange) allowUserChangeCheckbox = toolkit.createButton( composite, "Enable Allow User Change", SWT.CHECK ); allowUserChangeCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Safe Modify (pwdSafeModify) safeModifyCheckbox = toolkit.createButton( composite, "Enable Safe Modify", SWT.CHECK ); safeModifyCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); } /** * Creates the Lockout section. * * @param toolkit the toolkit to use * @param parent the parent composite */ private void createLockoutSection( FormToolkit toolkit, Composite parent ) { // Creation of the section Section section = toolkit.createSection( parent, Section.TITLE_BAR ); section.marginWidth = 10; section.setText( "Lockout" ); TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP ); td.grabHorizontal = true; section.setLayoutData( td ); Composite composite = toolkit.createComposite( section ); toolkit.paintBordersFor( composite ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); section.setClient( composite ); // Lockout (pwdLockout) lockoutCheckbox = toolkit.createButton( composite, "Enable Lockout", SWT.CHECK ); lockoutCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); // Lockout Duration (pwdLockoutDuration) toolkit.createLabel( composite, "Lockout Duration (seconds):" ); lockoutDurationText = toolkit.createText( composite, "" ); lockoutDurationText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Failure (pwdMaxFailure) toolkit.createLabel( composite, "Maximum Consecutive Failures (count):" ); maxFailureText = toolkit.createText( composite, "" ); maxFailureText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Failure Count Interval (pwdFailureCountInterval) toolkit.createLabel( composite, "Failure Count Interval (seconds):" ); failureCountIntervalText = toolkit.createText( composite, "" ); failureCountIntervalText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Max Idle (pwdMaxIdle) maxIdleCheckbox = toolkit.createButton( composite, "Enable Maximum Idle", SWT.CHECK ); maxIdleCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 3, 1 ) ); Composite maxIdleCheckboxRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Interval (seconds):" ); maxIdleText = toolkit.createText( maxIdleCheckboxRadioIndentComposite, "" ); maxIdleText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // In History (pwdInHistory) inHistoryCheckbox = toolkit.createButton( composite, "Enable In History", SWT.CHECK ); inHistoryCheckbox.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false, 2, 1 ) ); Composite inHistoryRadioIndentComposite = createRadioIndentComposite( toolkit, composite, "Used passwords stored in history:" ); inHistoryText = toolkit.createText( inHistoryRadioIndentComposite, "" ); inHistoryText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Minimum delay (pwdMinDelay) toolkit.createLabel( composite, "Mimimum Delay (seconds):" ); minimumDelayText = toolkit.createText( composite, "" ); minimumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); // Maximum Delay (pwdMaxDelay) toolkit.createLabel( composite, "Maximum Delay (seconds):" ); maximumDelayText = toolkit.createText( composite, "" ); maximumDelayText.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) ); } /** * Creates a radio indented composite. * * @param toolkit the toolkit * @param parent the parent composite * @return a radio indented composite */ private Composite createRadioIndentComposite( FormToolkit toolkit, Composite parent, String text ) { Composite composite = toolkit.createComposite( parent ); GridLayout gridLayout = new GridLayout( 3, false ); gridLayout.marginHeight = gridLayout.marginWidth = 0; composite.setLayout( gridLayout ); composite.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) ); toolkit.createLabel( composite, " " ); toolkit.createLabel( composite, text ); return composite; } /** * Adds listeners to UI fields. */ private void addListeners() { enabledCheckbox.addSelectionListener( buttonSelectionListener ); idText.addModifyListener( textModifyListener ); descriptionText.addModifyListener( textModifyListener ); checkQualityComboViewer.addSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.addSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.addModifyListener( textModifyListener ); minimumLengthCheckbox.addSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.addSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.addModifyListener( textModifyListener ); minimumLengthText.addVerifyListener( integerVerifyListener ); maximumLengthCheckbox.addSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.addSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.addModifyListener( textModifyListener ); maximumLengthText.addVerifyListener( integerVerifyListener ); minimumAgeText.addModifyListener( textModifyListener ); minimumAgeText.addVerifyListener( integerVerifyListener ); maximumAgeText.addModifyListener( textModifyListener ); maximumAgeText.addVerifyListener( integerVerifyListener ); expireWarningCheckbox.addSelectionListener( buttonSelectionListener ); expireWarningCheckbox.addSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.addModifyListener( textModifyListener ); expireWarningText.addVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.addSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.addSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.addModifyListener( textModifyListener ); graceAuthenticationLimitText.addVerifyListener( integerVerifyListener ); graceExpireCheckbox.addSelectionListener( buttonSelectionListener ); graceExpireCheckbox.addSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.addModifyListener( textModifyListener ); graceExpireText.addVerifyListener( integerVerifyListener ); mustChangeCheckbox.addSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.addSelectionListener( buttonSelectionListener ); safeModifyCheckbox.addSelectionListener( buttonSelectionListener ); lockoutCheckbox.addSelectionListener( buttonSelectionListener ); lockoutDurationText.addModifyListener( textModifyListener ); lockoutDurationText.addVerifyListener( integerVerifyListener ); maxFailureText.addModifyListener( textModifyListener ); maxFailureText.addVerifyListener( integerVerifyListener ); failureCountIntervalText.addModifyListener( textModifyListener ); failureCountIntervalText.addVerifyListener( integerVerifyListener ); maxIdleCheckbox.addSelectionListener( buttonSelectionListener ); maxIdleCheckbox.addSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.addModifyListener( textModifyListener ); maxIdleText.addVerifyListener( integerVerifyListener ); inHistoryCheckbox.addSelectionListener( buttonSelectionListener ); inHistoryCheckbox.addSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.addModifyListener( textModifyListener ); inHistoryText.addVerifyListener( integerVerifyListener ); minimumDelayText.addModifyListener( textModifyListener ); minimumDelayText.addVerifyListener( integerVerifyListener ); maximumDelayText.addModifyListener( textModifyListener ); maximumDelayText.addVerifyListener( integerVerifyListener ); } /** * Removes listeners to UI fields. */ private void removeListeners() { enabledCheckbox.removeSelectionListener( buttonSelectionListener ); idText.removeModifyListener( textModifyListener ); descriptionText.removeModifyListener( textModifyListener ); checkQualityComboViewer.removeSelectionChangedListener( viewerSelectionChangedListener ); checkQualityComboViewer.removeSelectionChangedListener( checkQualityComboViewerSelectionChangedListener ); validatorText.removeModifyListener( textModifyListener ); minimumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); minimumLengthCheckbox.removeSelectionListener( minimumLengthCheckboxSelectionListener ); minimumLengthText.removeModifyListener( textModifyListener ); minimumLengthText.removeVerifyListener( integerVerifyListener ); maximumLengthCheckbox.removeSelectionListener( buttonSelectionListener ); maximumLengthCheckbox.removeSelectionListener( maximumLengthCheckboxSelectionListener ); maximumLengthText.removeModifyListener( textModifyListener ); maximumLengthText.removeVerifyListener( integerVerifyListener ); minimumAgeText.removeModifyListener( textModifyListener ); minimumAgeText.removeVerifyListener( integerVerifyListener ); maximumAgeText.removeModifyListener( textModifyListener ); maximumAgeText.removeVerifyListener( integerVerifyListener ); expireWarningCheckbox.removeSelectionListener( buttonSelectionListener ); expireWarningCheckbox.removeSelectionListener( expireWarningCheckboxSelectionListener ); expireWarningText.removeModifyListener( textModifyListener ); expireWarningText.removeVerifyListener( integerVerifyListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( buttonSelectionListener ); graceAuthenticationLimitCheckbox.removeSelectionListener( graceAuthenticationLimitCheckboxSelectionListener ); graceAuthenticationLimitText.removeModifyListener( textModifyListener ); graceAuthenticationLimitText.removeVerifyListener( integerVerifyListener ); graceExpireCheckbox.removeSelectionListener( buttonSelectionListener ); graceExpireCheckbox.removeSelectionListener( graceExpireCheckboxSelectionListener ); graceExpireText.removeModifyListener( textModifyListener ); graceExpireText.removeVerifyListener( integerVerifyListener ); mustChangeCheckbox.removeSelectionListener( buttonSelectionListener ); allowUserChangeCheckbox.removeSelectionListener( buttonSelectionListener ); safeModifyCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutCheckbox.removeSelectionListener( buttonSelectionListener ); lockoutDurationText.removeModifyListener( textModifyListener ); lockoutDurationText.removeVerifyListener( integerVerifyListener ); maxFailureText.removeModifyListener( textModifyListener ); maxFailureText.removeVerifyListener( integerVerifyListener ); failureCountIntervalText.removeModifyListener( textModifyListener ); failureCountIntervalText.removeVerifyListener( integerVerifyListener ); maxIdleCheckbox.removeSelectionListener( buttonSelectionListener ); maxIdleCheckbox.removeSelectionListener( maxIdleCheckboxSelectionListener ); maxIdleText.removeModifyListener( textModifyListener ); maxIdleText.removeVerifyListener( integerVerifyListener ); inHistoryCheckbox.removeSelectionListener( buttonSelectionListener ); inHistoryCheckbox.removeSelectionListener( inHistoryCheckboxSelectionListener ); inHistoryText.removeModifyListener( textModifyListener ); inHistoryText.removeVerifyListener( integerVerifyListener ); minimumDelayText.removeModifyListener( textModifyListener ); minimumDelayText.removeVerifyListener( integerVerifyListener ); maximumDelayText.removeModifyListener( textModifyListener ); maximumDelayText.removeVerifyListener( integerVerifyListener ); } /** * {@inheritDoc} */ public void selectionChanged( IFormPart part, ISelection selection ) { IStructuredSelection ssel = ( IStructuredSelection ) selection; if ( ssel.size() == 1 ) { passwordPolicy = ( PasswordPolicyBean ) ssel.getFirstElement(); } else { passwordPolicy = null; } refresh(); } /** * {@inheritDoc} */ public void commit( boolean onSave ) { if ( passwordPolicy != null ) { // Enabled passwordPolicy.setEnabled( enabledCheckbox.getSelection() ); // ID passwordPolicy.setPwdId( ServerConfigurationEditorUtils.checkEmptyString( idText.getText() ) ); // Description passwordPolicy .setDescription( ServerConfigurationEditorUtils.checkEmptyString( descriptionText.getText() ) ); // Check Quality passwordPolicy.setPwdCheckQuality( getPwdCheckQuality() ); // Validator passwordPolicy .setPwdValidator( ServerConfigurationEditorUtils.checkEmptyString( validatorText.getText() ) ); // Miminum Length if ( minimumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMinLength( Integer.parseInt( minimumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinLength( 0 ); } } else { passwordPolicy.setPwdMinLength( 0 ); } // Maximum Length if ( maximumLengthCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxLength( Integer.parseInt( maximumLengthText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxLength( 0 ); } } else { passwordPolicy.setPwdMaxLength( 0 ); } // Minimum Age try { passwordPolicy.setPwdMinAge( Integer.parseInt( minimumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinAge( 0 ); } // Maximum Age try { passwordPolicy.setPwdMaxAge( Integer.parseInt( maximumAgeText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxAge( 0 ); } // Expire Warning if ( expireWarningCheckbox.getSelection() ) { try { passwordPolicy.setPwdExpireWarning( Integer.parseInt( expireWarningText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdExpireWarning( 0 ); } } else { passwordPolicy.setPwdExpireWarning( 0 ); } // Grace Authentication Limit if ( graceAuthenticationLimitCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceAuthNLimit( Integer.parseInt( graceAuthenticationLimitText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } } else { passwordPolicy.setPwdGraceAuthNLimit( 0 ); } // Grace Expire if ( graceExpireCheckbox.getSelection() ) { try { passwordPolicy.setPwdGraceExpire( Integer.parseInt( graceExpireText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdGraceExpire( 0 ); } } else { passwordPolicy.setPwdGraceExpire( 0 ); } // Must Change passwordPolicy.setPwdMustChange( mustChangeCheckbox.getSelection() ); // Allow User Change passwordPolicy.setPwdAllowUserChange( allowUserChangeCheckbox.getSelection() ); // Safe Modify passwordPolicy.setPwdSafeModify( safeModifyCheckbox.getSelection() ); // Lockout passwordPolicy.setPwdLockout( lockoutCheckbox.getSelection() ); // Lockout Duration try { passwordPolicy.setPwdLockoutDuration( Integer.parseInt( lockoutDurationText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdLockoutDuration( 0 ); } // Max Failure try { passwordPolicy.setPwdMaxFailure( Integer.parseInt( maxFailureText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxFailure( 0 ); } // Failure Count Interval try { passwordPolicy.setPwdFailureCountInterval( Integer.parseInt( failureCountIntervalText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdFailureCountInterval( 0 ); } // Max Idle if ( maxIdleCheckbox.getSelection() ) { try { passwordPolicy.setPwdMaxIdle( Integer.parseInt( maxIdleText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxIdle( 0 ); } } else { passwordPolicy.setPwdMaxIdle( 0 ); } // In History if ( inHistoryCheckbox.getSelection() ) { try { passwordPolicy.setPwdInHistory( Integer.parseInt( inHistoryText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdInHistory( 0 ); } } else { passwordPolicy.setPwdInHistory( 0 ); } // Minimum Delay try { passwordPolicy.setPwdMinDelay( Integer.parseInt( minimumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMinDelay( 0 ); } // Maximum Delay try { passwordPolicy.setPwdMaxDelay( Integer.parseInt( maximumDelayText.getText() ) ); } catch ( NumberFormatException e ) { passwordPolicy.setPwdMaxDelay( 0 ); } } } /** * Gets the password policy check quality. * * @return the password policy check quality */ private int getPwdCheckQuality() { IStructuredSelection selection = ( StructuredSelection ) checkQualityComboViewer.getSelection(); if ( !selection.isEmpty() ) { CheckQuality checkQuality = ( CheckQuality ) selection.getFirstElement(); return checkQuality.getValue(); } return CheckQuality.DISABLED.getValue(); } /** * {@inheritDoc} */ public void dispose() { } /** * {@inheritDoc} */ public void initialize( IManagedForm form ) { this.mform = form; } /** * {@inheritDoc} */ public boolean isDirty() { return false; } /** * {@inheritDoc} */ public boolean isStale() { return false; } /** * {@inheritDoc} */ public void refresh() { removeListeners(); if ( passwordPolicy != null ) { // Checking if this is the default password policy boolean isDefaultPasswordPolicy = PasswordPoliciesPage.isDefaultPasswordPolicy( passwordPolicy ); // Enabled enabledCheckbox.setSelection( passwordPolicy.isEnabled() ); // ID idText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdId() ) ); idText.setEnabled( !isDefaultPasswordPolicy ); // Description descriptionText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getDescription() ) ); descriptionText.setEnabled( !isDefaultPasswordPolicy ); // Check Quality checkQualityComboViewer.setSelection( new StructuredSelection( CheckQuality.valueOf( passwordPolicy .getPwdCheckQuality() ) ) ); // Validator validatorText.setText( ServerConfigurationEditorUtils.checkNull( passwordPolicy.getPwdValidator() ) ); // Miminum Length int minimumLength = passwordPolicy.getPwdMinLength(); minimumLengthCheckbox.setSelection( minimumLength != 0 ); minimumLengthText.setText( "" + minimumLength ); // Maximum Length int maximumLength = passwordPolicy.getPwdMaxLength(); maximumLengthCheckbox.setSelection( maximumLength != 0 ); maximumLengthText.setText( "" + maximumLength ); if ( getPwdCheckQuality() == 0 ) { minimumLengthCheckbox.setEnabled( false ); minimumLengthText.setEnabled( false ); maximumLengthCheckbox.setEnabled( false ); maximumLengthText.setEnabled( false ); } else { minimumLengthCheckbox.setEnabled( true ); minimumLengthText.setEnabled( minimumLength != 0 ); maximumLengthCheckbox.setEnabled( true ); maximumLengthText.setEnabled( maximumLength != 0 ); } // Minimum Age minimumAgeText.setText( "" + passwordPolicy.getPwdMinAge() ); // Maximum Age maximumAgeText.setText( "" + passwordPolicy.getPwdMaxAge() ); // Expire Warning int expireWarning = passwordPolicy.getPwdExpireWarning(); expireWarningCheckbox.setSelection( expireWarning != 0 ); expireWarningText.setText( "" + expireWarning ); expireWarningText.setEnabled( expireWarning != 0 ); // Grace Authentication Limit int graceAuthenticationLimit = passwordPolicy.getPwdGraceAuthNLimit(); graceAuthenticationLimitCheckbox.setSelection( graceAuthenticationLimit != 0 ); graceAuthenticationLimitText.setText( "" + graceAuthenticationLimit ); graceAuthenticationLimitText.setEnabled( graceAuthenticationLimit != 0 ); // Grace Expire int graceExpire = passwordPolicy.getPwdGraceExpire(); graceExpireCheckbox.setSelection( graceExpire != 0 ); graceExpireText.setText( "" + graceExpire ); graceExpireText.setEnabled( graceExpire != 0 ); // Must Change mustChangeCheckbox.setSelection( passwordPolicy.isPwdMustChange() ); // Allow User Change allowUserChangeCheckbox.setSelection( passwordPolicy.isPwdAllowUserChange() ); // Safe Modify safeModifyCheckbox.setSelection( passwordPolicy.isPwdSafeModify() ); // Lockout lockoutCheckbox.setSelection( passwordPolicy.isPwdLockout() ); // Lockout Duration lockoutDurationText.setText( "" + passwordPolicy.getPwdLockoutDuration() ); // Max Failure maxFailureText.setText( "" + passwordPolicy.getPwdMaxFailure() ); // Failure Count Interval failureCountIntervalText.setText( "" + passwordPolicy.getPwdFailureCountInterval() ); // Max Idle int maxIdle = passwordPolicy.getPwdMaxIdle(); maxIdleCheckbox.setSelection( maxIdle != 0 ); maxIdleText.setText( "" + maxIdle ); maxIdleText.setEnabled( maxIdle != 0 ); // In History int inHistory = passwordPolicy.getPwdInHistory(); inHistoryCheckbox.setSelection( inHistory != 0 ); inHistoryText.setText( "" + inHistory ); inHistoryText.setEnabled( inHistory != 0 ); // Minimum Delay minimumDelayText.setText( "" + passwordPolicy.getPwdMinDelay() ); // Maximum Delay maximumDelayText.setText( "" + passwordPolicy.getPwdMaxDelay() ); } addListeners(); } /** * {@inheritDoc} */ public void setFocus() { // idText.setFocus(); } /** * {@inheritDoc} */ public boolean setFormInput( Object input ) { return false; } /** * This enum is used for the check quality value. * * @author Apache Directory Project */ private enum CheckQuality { DISABLED(0), RELAXED(1), STRICT(2); /** The value */ private int value; /** * Creates a new instance of CheckQuality. * * @param value the value */ private CheckQuality( int value ) { this.value = value; } /** * Gets the value. * * @return the value */ public int getValue() { return value; } public static CheckQuality valueOf( int value ) { for ( CheckQuality checkQuality : CheckQuality.class.getEnumConstants() ) { if ( checkQuality.getValue() == value ) { return checkQuality; } } throw new IllegalArgumentException( "There is no CheckQuality value for :" + value ); } /** * {@inheritDoc} */ public String toString() { switch ( this ) { case DISABLED: return "Disabled"; case RELAXED: return "Relaxed"; case STRICT: return "Strict"; } return super.toString(); } } }
blob 1: long method, 2: data class t t f 1: long method, 2: data class blob 0 14167 https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/apacheds.configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/PasswordPolicyDetailsPage.java/#L110-L1248 1 2338 14167
1009      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); }
feature envy long method, data class t t f long method, data class feature envy 0 9269 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 1 1009 9269
173    { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; }
long method long method, data class t t t  data class   0 2041 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 1 173 2041
1615  {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } }
long method Data Class, Long Method t f t Data Class   0 11472 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 1 1615 11472
2427  {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } }
feature envy long method, data class t t f long method, data class feature envy 0 14446 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 1 2427 14446
1281 { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class", "2. Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } }
blob 1. data class, 2. long method t t f 1. data class, 2. long method blob 0 10595 https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 1 1281 10595
1012    { "message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void write(DataOutputView out) throws IOException { out.writeInt(position); for (int i = 0; i < position; i++) { out.writeDouble(data[i]); } }
feature envy long method, data class t t f long method, data class feature envy 0 9274 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/DoubleValueArray.java/#L179-L186 1 1012 9274
1682 {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
} ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) {
long method Data Class, Long Method t f t Data Class   0 11682 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 1 1682 11682
1631 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } }
blob data class, long method t t f data class, long method blob 0 11508 https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 1 1631 11508
345     { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); }
long method 1. long method, 2. data class t t f  2. data class long method 0 3519 https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 1 345 3519
881 { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MainFragment extends Fragment implements Updatable { /** * The {@link SwipeRefreshLayout.OnRefreshListener} is also an {@link Observable}. It is * observed by the {@link UsernamesRepository}, an update is triggered whenever * {@link SwipeRefreshLayout.OnRefreshListener#onRefresh()} is fired. */ private OnRefreshObservable refreshObservable; /** * The {@link UsernamesRepository} takes care of providing the data to this fragment. It is an * {@link Updatable} because changes in the {@link OnRefreshObservable} require that it updates * its list of usernames. It is also an {@link Observable} and is observed by this MainFragment. */ private UsernamesRepository usernamesRepository; private ListAdapter listAdapter; private ListView listView; private SwipeRefreshLayout swipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.main_frag, container, false); listView = (ListView) root.findViewById(R.id.list); // Set pull to refresh as an observable and attach it to the view refreshObservable = new OnRefreshObservable(); swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.refresh_layout); swipeRefreshLayout.setColorSchemeColors( ContextCompat.getColor(getActivity(), R.color.colorPrimary), ContextCompat.getColor(getActivity(), R.color.colorAccent), ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark)); swipeRefreshLayout.setOnRefreshListener(refreshObservable); // Initialise the repository usernamesRepository = new UsernamesRepository(new UsernamesFetcher()); return root; } @Override public void onResume() { super.onResume(); // We make sure the repository observes the refresh listener refreshObservable.addUpdatable(usernamesRepository); /** * We make sure the main fragment observes the repository. This will also trigger the * repository to update itself, via * {@link UsernamesRepository#firstUpdatableAdded(UpdateDispatcher)}. */ usernamesRepository.addUpdatable(this); /** * We update the UI to show the data is being updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); } }); } @Override public void onPause() { super.onPause(); // We remove the observations to avoid triggering updates when they aren't needed refreshObservable.removeUpdatable(usernamesRepository); usernamesRepository.removeUpdatable(this); } /** * As this MainFragment is observing the {@link UsernamesRepository}, this is triggered * whenever the {@link UsernamesRepository} updates itself. */ @Override public void update() { /** * We update the UI to show the data has been updated. We need to wait for the * {@link swipeRefreshLayout} to be ready before asking it to show itself as not refreshing. */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); } }); // Check error status if (usernamesRepository.isError()) { // Show error message, do not update list as we still want to show the last known list of // usernames Toast.makeText(getContext(), getResources().getString(R.string.error), Toast.LENGTH_LONG).show(); } else { // Update the list of usernames listAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, usernamesRepository.get()); listView.setAdapter(listAdapter); } } }
blob long method, data class t t f long method, data class blob 0 8020 https://github.com/google/agera/blob/04045ccbf41ac5fc6806724127b33cbe0dda372c/samples/BasicSample/app/src/main/java/com/example/android/agera/basicsample/MainFragment.java/#L42-L150 1 881 8020
25      { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Key)) { return false; } Key key = (Key) o; return annotationType.equals(key.annotationType) && type.equals(key.type); }
feature envy data class t t f data class feature envy 0 693 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/commons/che-core-commons-inject/src/main/java/org/eclipse/che/inject/lifecycle/LifecycleModule.java/#L40-L50 1 25 693
1920 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } }
blob data class, long method t t f data class, long method blob 0 12413 https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 1 1920 12413
777 {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); }
blob data class t t f data class blob 0 7370 https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 1 777 7370
2166   Yes, I found bad smells(the bad smells are: 1. Long method 2. Data class 3. Feature envy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); }
long method  Long method2 Data class3 Feature envy t f t     0 13348 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 2 2166 13348
5535  YES I found bad smells the bad smells are: Data class, Long method The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); }
long method  Data class, Long method t f t  Data class   0 6189 https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 1 5535 6189
2350 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } }
blob long method, data class t t f long method, data class blob 0 14205 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 1 2350 14205
1507 {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } }
blob data class, long method t t f data class, long method blob 0 11152 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 1 1507 11152
762   { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; }
long method long method, data class t t t  data class   0 7113 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 1 762 7113
150     {"message": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) }
blob data class, long method t t f data class, long method blob 0 1904 https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 1 150 1904
525   YES I found bad smells the bad smells are: 1. Long class 2. Long method (createConsumer, onEvent, isMatching, isWildcarded) 3. Feature envy 4. Data class/misplaced responsibilities 5. Primitive obsession 6. Inappropriate intimacy 7. Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property) 8. Message chain (engine.start() accessed through multiple levels of abstraction) 9. Duplicated code (multiple if statements checking for wildcarded session identifier) 10. Dead code (some methods never called) 11. Comments suggesting magic values/hidden intent (// clear list of consumers) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } }
blob  Long class2 Long method (createConsumer, onEvent, isMatching, isWildcarded)3 Feature envy4 Data class/misplaced responsibilities5 Primitive obsession6 Inappropriate intimacy7 Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property)8 Message chain (enginestart() accessed through multiple levels of abstraction)9 Duplicated code (multiple if statements checking for wildcarded session identifier) t f f . Long class2. Long method (createConsumer, onEvent, isMatching, isWildcarded)3. Feature envy4. Data class/misplaced responsibilities5. Primitive obsession6. Inappropriate intimacy7. Inconsistent parameter type (lazyCreateEngine boolean parameter versus component's property)8. Message chain (engine.start() accessed through multiple levels of abstraction)9. Duplicated code (multiple if statements checking for wildcarded session identifier) blob 0 5430 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 2 525 5430
261 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); }
long method long method, data class t t t  data class   0 2843 https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 1 261 2843
1649 {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } }
blob data class t t f data class blob 0 11566 https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 1 1649 11566
1856  YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } }
blob  Long method2 Feature envy3 Data class4 Primitive obsession t f f . Long method2. Feature envy3. Data class4. Primitive obsession blob 0 12215 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 2 1856 12215
4398    { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } }
long method long method, data class t t t  data class   0 11629 https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 1 4398 11629
1349    { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; }
feature envy long method, data class t t f long method, data class feature envy 0 10754 https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 1 1349 10754
1691    { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } }
blob Data Class t f f Data Class blob 0 11710 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 1 1691 11710
2699      { "output": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } }
long method long method, data class t t t  data class   0 15326 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 1 2699 15326
2519 { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; }
long method 1. long method, 2. data class t t t  2. data class   0 14706 https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 1 2519 14706
1648 {"response": "YES I found bad smells the bad smells are: 1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void write(org.apache.thrift.protocol.TProtocol oprot, handle_hms_notification_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); }
feature envy 1. data class t t f 1. data class feature envy 0 11565 https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-hdfs/sentry-hdfs-common/src/gen/thrift/gen-javabean/org/apache/sentry/hdfs/service/thrift/SentryHDFSService.java/#L1004-L1010 1 1648 11565
781     { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } }
long method long method, data class t t t  data class   0 7457 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 1 781 7457
168    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; }
blob long method, data class t t f long method, data class blob 0 2029 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 1 168 2029
177 {"answer":"YES I found bad smells","the bad smells are: 1. Blob, 2. Long Method, 3. Long Parameter List, 4. Data Class, 5. Feature Envy, 6. Long Method, 7. Long Parameter List, 8. Data Class, 9. Feature Envy, 10. Long Method, 11. Long Parameter List, 12. Data Class, 13. Feature Envy, 14. Long Method, 15. Blob, 16. Long Parameter List, 17. Data Class, 18. Feature Envy, 19. Long Method, 20. Blob, 21. Long Parameter List, 22. Data Class, 23. Long Method, 24. Blob, 25. Long Parameter List, 26. Data Class, 27. Feature Envy, 28. Long Method, 29. Blob, 30. Long Parameter List, 31. Data Class, 32. Feature Envy, 33. Long Method, 34. Blob, 35. Long Parameter List, 36. Data Class, 37. Feature Envy, 38. Long Method, 39. Blob, 40. Long Parameter List, 41. Data Class, 42. Feature Envy, 43. Long Method, 44. Blob, 45. Long Parameter List, 46. Data Class, 47. Feature Envy, 48. Long Method, 49. Blob, 50. Long Parameter List, 51. Data Class, 52. Feature Envy, 53. Long Method, 54. Blob, 55. Long Parameter List, 56. Data Class, 57. Feature Envy, 58. Long Method, 59. Long Parameter List, 60. Data Class, 61. Feature Envy, 62. Long Method, 63. Long Parameter List, 64. Data Class, 65. Feature Envy, 66. Long Method, 67. Long Parameter List, 68. Data Class, 69. Feature Envy, 70. Long Method, 71. Blob, 72. Data Class, 73. Long Method, 74. Blob, 75. Data Class, 76. Long Method, 77. Blob, 78. Data Class, 79. Long Method, 80. Blob, 81. Data Class, 82. Long Method, 83. Blob, 84. Data Class, 85. Long Method, 86. Blob, 87. Data Class, 88. Long Method, 89. Blob, 90. Data Class, 91. Long Method, 92. Long Parameter List, 93. Data Class, 94. Feature Envy, 95. Long Method, 96. Long Parameter List, 97. Data Class, 98. Feature Envy, 99. Long Method, 100. Long Parameter List, 101. Data Class, 102. Feature Envy, 103. Long Method, 104. Long Parameter List, 105. Data Class, 106. Feature Envy, 107. Long Method, 108. Long Parameter List, 109. Data Class, 110. Feature Envy, 111. Long Method, 112. Long Parameter List, 113. Data Class, 114. Feature Envy, 115. Long Method, 116. Long Parameter List, 117. Data Class, 118. Feature Envy, 119. Long Method, 120. Long Parameter List, 121. Data Class, 122. Feature Envy, 123. Long Method, 124. Long Parameter List, 125. Data Class, 126. Feature Envy, 127. Long Method, 128. Long Parameter List, 129. Data Class, 130. Feature Envy, 131. Long Method, 132. Long Parameter List, 133. Data Class, 134. Feature Envy, 135. Long Method, 136. Long Parameter List, 137. Data Class, 138. Feature Envy, 139. Long Method, 140. Long Parameter List, 141. Data Class, 142. Feature Envy, 143. Long Method, 144. Long Parameter List, 145. Data Class, 146. Feature Envy, 147. Long Method, 148. Long Parameter List, 149. Data Class, 150. Feature Envy, 151. Long Method, 152. Long Parameter List, 153. Data Class, 154. Feature Envy, 155. Long Method, 156. Long Parameter List, 157. Data Class, 158. Feature Envy, 159. Long Method, 160. Long Parameter List, 161. Data Class, 162. Feature Envy, 163. Long Method, 164. Long Parameter List, 165. Data Class, 166. Feature Envy, 167. Long Method, 168. Long Parameter List, 169. Data Class, 170. Feature Envy, 171. Long Method, 172. Long Parameter List, 173. Data Class, 174. Feature Envy, 175. Blob, 176. Data Class, 177. Feature Envy, 178. Long Method, 179. Blob, 180. Data Class, 181. Feature Envy, 182. Long Method, 183. Blob, 184. Data Class, 185. Feature Envy, 186. Long Method, 187. Blob, 188. Long Parameter List, 189. Data Class, 190. Feature Envy, 191. Long Method, 192. Blob, 193. Long Parameter List, 194. Data Class, 195. Feature Envy, 196. Long Method, 197. Blob, 198. Long Parameter List, 199. Data Class, 200. Feature Envy, 201. Blob, 202. Data Class, 203. Feature Envy, 204. Long Method, 205. Blob, 206. Data Class, 207. Feature Envy, 208. Long Method, 209. Blob, 210. Data Class, 211. Feature Envy, 212. Long Method, 213. Blob, 214. Data Class, 215. Feature Envy, 216. Long Method, 217. Blob, 218. Data Class, 219. Feature Envy, 220. Long Method, 221. Blob, 222. Data Class, 223. Feature Envy, 224. Long Method, 225. Blob, 226. Data Class, 227. Feature Envy, 228. Long Method, 229. Blob, 230. Data Class, 231. Feature Envy, 232. Long Method, 233. Long Parameter List, 234. Data Class, 235. Feature Envy, 236. Long Method, 237. Long Parameter List, 238. Data Class, 239. Feature Envy, 240. Long Method, 241. Long Parameter List, 242. Data Class, 243. Feature Envy, 244. Long Method, 245. Long Parameter List, 246. Data Class, 247. Feature Envy, 248. Long Method, 249. Long Parameter List, 250. Data Class, 251. Feature Envy, 252. Long Method, 253. Long Parameter List, 254. Data Class, 255. Feature Envy, 256. Long Method, 257. Long Parameter List, 258. Data Class, 259. Feature Envy, 260. Long Method, 261. Long Parameter List, 262. Data Class, 263. Feature Envy, 264. Long Method, 265. Long Parameter List, 266. Data Class, 267. Feature Envy, 268. Long Method, 269. Long Parameter List, 270. Data Class, 271. Feature Envy, 272. Long Method, 273. Long Parameter List, 274. Data Class, 275. Feature Envy, 276. Long Method, 277. Long Parameter List, 278. Data Class, 279. Feature Envy, 280. Long Method, 281. Long Parameter List, 282. Data Class, 283. Feature Envy, 284. Long Method, 285. Long Parameter List, 286. Data Class, 287. Feature Envy, 288. Long Method, 289. Long Parameter List, 290. Data Class, 291. Feature Envy, 292. Long Method, 293. Long Parameter List, 294. Data Class, 295. Feature Envy, 296. Long Method, 297. Long Parameter List, 298. Data Class, 299. Feature Envy, 300. Long Method, 301. Long Parameter List, 302. Data Class, 303. Feature Envy, 304. Long Method, 305. Long Parameter List, 306. Data Class, 307. Feature Envy, 308. Long Method, 309. Long Parameter List, 310. Data Class, 311. Feature Envy, 312. Long Method, 313. Long Parameter List, 314. Data Class, 315. Feature Envy, 316. Long Method, 317. Long Parameter List, 318. Data Class, 319. Feature Envy, 320. Long Method, 321. Long Parameter List, 322. Data Class, 323. Feature Envy, 324. Long Method, 325. Long Parameter List, 326. Data Class, 327. Feature Envy, 328. Long Method, 329. Long Parameter List, 330. Data Class, 331. Feature Envy, 332. Long Method, 333. Long Parameter List, 334. Data Class, 335. Feature Envy, 336. Long Method, 337. Long Parameter List, 338. Data Class, 339. Feature Envy, 340. Long Method, 341. Long Parameter List, 342. Data Class, 343. Feature Envy, 344. Long Method, 345. Long Parameter List, 346. Data Class, 347. Feature Envy, 348. Long Method, 349. Long Parameter List, 350. Data Class, 351. Feature Envy, 352. Long Method, 353. Long Parameter List, 354. Data Class, 355. Feature Envy, 356. Long Method, 357. Long Parameter List, 358. Data Class, 359. Feature Envy, 360. Long Method, 361. Long Parameter List, 362. Data Class, 363. Feature Envy, 364. Long Method, 365. Long Parameter List, 366. Data Class, 367. Feature Envy, 368. Long Method, 369. Long Parameter List, 370. Data Class, 371. Feature Envy, 372. Long Method, 373. Long Parameter List, 374. Data Class, 375. Feature Envy, 376. Long Method, 377. Long Parameter List, 378. Data Class, 379. Feature Envy, 380. Long Method, 381. Long Parameter List, 382. Data Class, 383. Feature Envy, 384. Long Method, 385. Long Parameter List, 386. Data Class, 387. Feature Envy, 388. Long Method, 389. Long Parameter List, 390. Data Class, 391. Feature Envy, 392. Long Method, 393. Long Parameter List, 394. Data Class, 395. Feature Envy, 396. Long Method, 397. Long Parameter List, 398. Data Class, 399. Feature Envy, 400. Long Method, 401. Long Parameter List, 402. Data Class, 403. Feature Envy, 404. Long Method, 405. Long Parameter List, 406. Data Class, 407. Feature Envy, 408. Long Method, 409. Long Parameter List, 410. Data Class, 411. Feature Envy, 412. Long Method, 413. Long Parameter List, 414. Data Class, 415. Feature Envy, 416. Long Method, 417. Long Parameter List, 418. Data Class, 419. Feature Envy, 420. Long Method, 421. Long Parameter List, 422. Data Class, 423. Feature Envy, 424. Long Method, 425. Long Parameter List, 426. Data Class, 427. Feature Envy, 428. Long Method, 429. Data Class, 430. Feature Envy, 431. Long Method, 432. Long Parameter List, 433. Data Class, 434. Feature Envy, 435. Long Method, 436. Long Parameter List, 437. Data Class, 438. Feature Envy, 439. Long Method, 440. Long Parameter List, 441. Data Class, 442. Feature Envy, 443. Long Method, 444. Blob, 445. Data Class, 446. Feature Envy, 447. Long Method, 448. Blob, 449. Data Class, 450. Feature Envy, 451. Long Method, 452. Blob, 453. Data Class, 454. Feature Envy, 455. Long Method, 456. Blob, 457. Long Parameter List, 458. Data Class, 459. Feature Envy, 460. Long Method, 461. Blob, 462. Long Parameter List, 463. Data Class, 464. Feature Envy, 465. Long Method, 466. Blob, 467. Long Parameter List, 468. Data Class, 469. Feature Envy, 470. Long Method, 471. Blob, 472. Long Parameter List, 473. Data Class, 474. Feature Envy, 475. Long Method, 476. Data Class, 477. Feature Envy, 478. Long Method, 479. Blob, 480. Data Class, 481. Feature Envy, 482. Long Method, 483. Blob, 484. Data Class, 485. Feature Envy, 486. Long Method, 487. Blob, 488. Data Class, 489. Feature Envy, 490. Long Method, 491. Blob, 492. Data Class, 493. Feature Envy, 494. Long Method, 495. Blob, 496. Data Class, 497. Feature Envy, 498. Long Method, 499. Data Class, 500. Feature Envy, 501. Long Method, 502. Blob, 503. Data Class, 504. Feature Envy, 505. Long Method, 506. Blob, 507. Data Class, 508. Feature Envy, 509. Long Method, 510. Blob, 511. Data Class, 512. Feature Envy, 513. Long Method, 514. Blob, 515. Data Class, 516. Feature Envy, 517. Long Method, 518. Blob, 519. Data Class, 520. Feature Envy, 521. Long Method, 522. Blob, 523. Data Class, 524. Feature Envy, 525. Long Method, 526. Blob, 527. Data Class, 528. Feature Envy, 529. Long Method, 530. Blob, 531. Data Class, 532. Feature Envy, 533. Long Method, 534. Blob, 535. Data Class, 536. Feature Envy, 537. Long Method, 538. Blob, 539. Data Class, 540. Feature Envy, 541. Long Method, 542. Blob, 543. Data Class, 544. Feature Envy, 545. Long Method, 546. Blob, 547. Data Class, 548. Feature Envy, 549. Long Method, 550. Blob, 551. Data Class, 552. Feature Envy, 553. Long Method, 554. Blob, 555. Data Class, 556. Feature Envy, 557. Long Method, 558. Blob, 559. Data Class, 560. Feature Envy, 561. Long Method, 562. Blob, 563. Data Class, 564. Feature Envy, 565. Long Method, 566. Blob, 567. Data Class, 568. Feature Envy, 569. Long Method, 570. Blob, 571. Data Class, 572. Feature Envy, 573. Long Method, 574. Blob, 575. Data Class, 576. Feature Envy, 577. Long Method, 578. Blob, 579. Data Class, 580. Feature Envy, 581. Long Method, 582. Blob, 583. Data Class, 584. Feature Envy, 585. Long Method, 586. Blob, 587. Data Class, 588. Feature Envy, 589. Long Method, 590. Blob, 591. Data Class, 592. Feature Envy, 593. Long Method, 594. Blob, 595. Data Class, 596. Feature Envy, 597. Long Method, 598. Blob, 599. Data Class, 600. Feature Envy, 601. Long Method, 602. Blob, 603. Data Class, 604. Feature Envy, 605. Long Method, 606. Blob, 607. Data Class, 608. Feature Envy, 609. Long Method, 610. Blob, 611. Data Class, 612. Feature Envy, 613. Long Method, 614. Blob, 615. Data Class, 616. Feature Envy, 617. Long Method, 618. Blob, 619. Data Class, 620. Feature Envy, 621. Long Method, 622. Blob, 623. Data Class, 624. Feature Envy, 625. Long Method, 626. Blob, 627. Data Class, 628. Feature Envy, 629. Long Method, 630. Blob, 631. Data Class, 632. Feature Envy, 633. Long Method, 634. Blob, 635. Data Class, 636. Feature Envy, 637. Long Method, 638. Blob, 639. Data Class, 640. Feature Envy, 641. Long Method, 642. Blob, 643. Data Class, 644. Feature Envy, 645. Long Method, 646. Blob, 647. Data Class, 648. Feature Envy, 649. Long Method, 650. Blob, 651. Data Class, 652. Feature Envy, 653 The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } }
blob  Blob, 2 Long Method, 3 Long Parameter List, 4 Data Class, 5 Feature Envy, 6 Long Method, 7 Long Parameter List, 8 Data Class, 9 Feature Envy, t f t  2. Long Method, 3. Long Parameter List, 4. Data Class, 5. Feature Envy, 6. Long Method, 7. Long Parameter List, 8. Data Class, 9. Feature Envy,   0 2053 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 1 177 2053
663   {"message": "YES I found bad smells", "bad_smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); }
feature envy long method, data class t t f long method, data class feature envy 0 6456 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 1 663 6456
4068  { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } }
blob blob, data class, long method t t t  data class, long method   0 10741 https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 1 4068 10741
1989  { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } }
blob long method, data class t t f long method, data class blob 0 12678 https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 1 1989 12678
1826  YES I found bad smells the bad smells are: 1.Long method 2.Magic number 3.Duplicate code 4.Message chains 5.Data class 6.Inappropriate intimacy 7.Shotgun surgery I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } }
long method Long method 2Magic number 3Duplicate code 4Message chains 5Data class 6Inappropriate intimacy7Shotgun surgery t f t     0 12112 https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 2 1826 12112
2446 {"response": "YES, I found bad smells", "bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); }
feature envy data class, long method t t f data class, long method feature envy 0 14496 https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 1 2446 14496
1946 { "answer": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ObserveUtil { /* keys used to populate the request context */ public static final String CTX_ENDPOINT = "leshan-endpoint"; public static final String CTX_REGID = "leshan-regId"; public static final String CTX_LWM2M_PATH = "leshan-path"; /** * Create a LWM2M observation from a CoAP request. */ public static Observation createLwM2mObservation(Request request) { String regId = null; String lwm2mPath = null; Map context = null; for (Entry ctx : request.getUserContext().entrySet()) { switch (ctx.getKey()) { case CTX_REGID: regId = ctx.getValue(); break; case CTX_LWM2M_PATH: lwm2mPath = ctx.getValue(); break; case CTX_ENDPOINT: break; default: if (context == null) { context = new HashMap<>(); } context.put(ctx.getKey(), ctx.getValue()); } } ContentFormat contentFormat = null; if (request.getOptions().hasAccept()) { contentFormat = ContentFormat.fromCode(request.getOptions().getAccept()); } return new Observation(request.getToken().getBytes(), regId, new LwM2mPath(lwm2mPath), contentFormat, context); } /** * Create a CoAP observe request context with specific keys needed for internal Leshan working. */ public static Map createCoapObserveRequestContext(String endpoint, String registrationId, ObserveRequest request) { Map context = new HashMap<>(); context.put(CTX_ENDPOINT, endpoint); context.put(CTX_REGID, registrationId); context.put(CTX_LWM2M_PATH, request.getPath().toString()); for (Entry ctx : request.getContext().entrySet()) { context.put(ctx.getKey(), ctx.getValue()); } return context; } public static String extractRegistrationId(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_REGID); } public static String extractLwm2mPath(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_LWM2M_PATH); } public static String extractEndpoint(org.eclipse.californium.core.observe.Observation observation) { return observation.getRequest().getUserContext().get(CTX_ENDPOINT); } /** * Validate the Californium observation. It is valid if it contains all necessary context for Leshan. */ public static String validateCoapObservation(org.eclipse.californium.core.observe.Observation observation) { if (!observation.getRequest().getUserContext().containsKey(CTX_REGID)) throw new IllegalStateException("missing registrationId info in the request context"); if (!observation.getRequest().getUserContext().containsKey(CTX_LWM2M_PATH)) throw new IllegalStateException("missing lwm2m path info in the request context"); String endpoint = observation.getRequest().getUserContext().get(CTX_ENDPOINT); if (endpoint == null) throw new IllegalStateException("missing endpoint info in the request context"); return endpoint; } }
blob data class t t f data class blob 0 12519 https://github.com/eclipse/leshan/blob/eb75fc8b7d5560944e6d532f1a09d5e5c6e54559/leshan-server-cf/src/main/java/org/eclipse/leshan/server/californium/ObserveUtil.java/#L32-L114 1 1946 12519
684 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static class createJob_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, createJob_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, createJob_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } }
blob long method, data class t t f long method, data class blob 0 6614 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/AuroraSchedulerManager.java/#L2760-L2805 1 684 6614
174 { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } }
blob long method, data class t t f long method, data class blob 0 2045 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 1 174 2045
1844 {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } }
blob long method, data class t t f long method, data class blob 0 12159 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 1 1844 12159
2412    { "message": "YES I found bad smells", "bad smells are:": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } }
blob long method, data class t t f long method, data class blob 0 14403 https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 1 2412 14403
3452 {"output":"YES I found bad smells\nthe bad smells are:\n1. Long Method\n2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PeriodFormatterData { final DataRecord dr; String localeName; // debug public static boolean trace = false; public PeriodFormatterData(String localeName, DataRecord dr) { this.dr = dr; this.localeName = localeName; if(localeName == null) { throw new NullPointerException("localename is null"); } // System.err.println("** localeName is " + localeName); if (dr == null) { // Thread.dumpStack(); throw new NullPointerException("data record is null"); } } // none - chinese (all forms the same) // plural - english, special form for 1 // dual - special form for 1 and 2 // paucal - russian, special form for 1, for 2-4 and n > 20 && n % 10 == 2-4 // rpt_dual_few - slovenian, special form for 1, 2, 3-4 and n as above // hebrew, dual plus singular form for years > 11 // arabic, dual, plus singular form for all terms > 10 /** * Return the pluralization format used by this locale. * @return the pluralization format */ public int pluralization() { return dr.pl; } /** * Return true if zeros are allowed in the display. * @return true if zeros should be allowed */ public boolean allowZero() { return dr.allowZero; } public boolean weeksAloneOnly() { return dr.weeksAloneOnly; } public int useMilliseconds() { return dr.useMilliseconds; } /** * Append the appropriate prefix to the string builder, depending on whether and * how a limit and direction are to be displayed. * * @param tl how and whether to display the time limit * @param td how and whether to display the time direction * @param sb the string builder to which to append the text * @return true if a following digit will require a digit prefix */ public boolean appendPrefix(int tl, int td, StringBuffer sb) { if (dr.scopeData != null) { int ix = tl * 3 + td; ScopeData sd = dr.scopeData[ix]; if (sd != null) { String prefix = sd.prefix; if (prefix != null) { sb.append(prefix); return sd.requiresDigitPrefix; } } } return false; } /** * Append the appropriate suffix to the string builder, depending on whether and * how a limit and direction are to be displayed. * * @param tl how and whether to display the time limit * @param td how and whether to display the time direction * @param sb the string builder to which to append the text */ public void appendSuffix(int tl, int td, StringBuffer sb) { if (dr.scopeData != null) { int ix = tl * 3 + td; ScopeData sd = dr.scopeData[ix]; if (sd != null) { String suffix = sd.suffix; if (suffix != null) { if (trace) { System.out.println("appendSuffix '" + suffix + "'"); } sb.append(suffix); } } } } /** * Append the count and unit to the string builder. * * @param unit the unit to append * @param count the count of units, * 1000 * @param cv the format to use for displaying the count * @param uv the format to use for displaying the unit * @param useCountSep if false, force no separator between count and unit * @param useDigitPrefix if true, use the digit prefix * @param multiple true if there are multiple units in this string * @param last true if this is the last unit * @param wasSkipped true if the unit(s) before this were skipped * @param sb the string builder to which to append the text * @return true if will require skip marker */ @SuppressWarnings("fallthrough") public boolean appendUnit(TimeUnit unit, int count, int cv, int uv, boolean useCountSep, boolean useDigitPrefix, boolean multiple, boolean last, boolean wasSkipped, StringBuffer sb) { int px = unit.ordinal(); boolean willRequireSkipMarker = false; if (dr.requiresSkipMarker != null && dr.requiresSkipMarker[px] && dr.skippedUnitMarker != null) { if (!wasSkipped && last) { sb.append(dr.skippedUnitMarker); } willRequireSkipMarker = true; } if (uv != EUnitVariant.PLURALIZED) { boolean useMedium = uv == EUnitVariant.MEDIUM; String[] names = useMedium ? dr.mediumNames : dr.shortNames; if (names == null || names[px] == null) { names = useMedium ? dr.shortNames : dr.mediumNames; } if (names != null && names[px] != null) { appendCount(unit, false, false, count, cv, useCountSep, names[px], last, sb); // omit suffix, ok? return false; // omit skip marker } } // check cv if (cv == ECountVariant.HALF_FRACTION && dr.halfSupport != null) { switch (dr.halfSupport[px]) { case EHalfSupport.YES: break; case EHalfSupport.ONE_PLUS: if (count > 1000) { break; } // else fall through to decimal case EHalfSupport.NO: { count = (count / 500) * 500; // round to 1/2 cv = ECountVariant.DECIMAL1; } break; } } String name = null; int form = computeForm(unit, count, cv, multiple && last); if (form == FORM_SINGULAR_SPELLED) { if (dr.singularNames == null) { form = FORM_SINGULAR; name = dr.pluralNames[px][form]; } else { name = dr.singularNames[px]; } } else if (form == FORM_SINGULAR_NO_OMIT) { name = dr.pluralNames[px][FORM_SINGULAR]; } else if (form == FORM_HALF_SPELLED) { name = dr.halfNames[px]; } else { try { name = dr.pluralNames[px][form]; } catch (NullPointerException e) { System.out.println("Null Pointer in PeriodFormatterData["+localeName+"].au px: " + px + " form: " + form + " pn: " + Arrays.toString(dr.pluralNames)); throw e; } } if (name == null) { form = FORM_PLURAL; name = dr.pluralNames[px][form]; } boolean omitCount = (form == FORM_SINGULAR_SPELLED || form == FORM_HALF_SPELLED) || (dr.omitSingularCount && form == FORM_SINGULAR) || (dr.omitDualCount && form == FORM_DUAL); int suffixIndex = appendCount(unit, omitCount, useDigitPrefix, count, cv, useCountSep, name, last, sb); if (last && suffixIndex >= 0) { String suffix = null; if (dr.rqdSuffixes != null && suffixIndex < dr.rqdSuffixes.length) { suffix = dr.rqdSuffixes[suffixIndex]; } if (suffix == null && dr.optSuffixes != null && suffixIndex < dr.optSuffixes.length) { suffix = dr.optSuffixes[suffixIndex]; } if (suffix != null) { sb.append(suffix); } } return willRequireSkipMarker; } /** * Append a count to the string builder. * * @param unit the unit * @param count the count * @param cv the format to use for displaying the count * @param useSep whether to use the count separator, if available * @param name the term name * @param last true if this is the last unit to be formatted * @param sb the string builder to which to append the text * @return index to use if might have required or optional suffix, or -1 if none required */ public int appendCount(TimeUnit unit, boolean omitCount, boolean useDigitPrefix, int count, int cv, boolean useSep, String name, boolean last, StringBuffer sb) { if (cv == ECountVariant.HALF_FRACTION && dr.halves == null) { cv = ECountVariant.INTEGER; } if (!omitCount && useDigitPrefix && dr.digitPrefix != null) { sb.append(dr.digitPrefix); } int index = unit.ordinal(); switch (cv) { case ECountVariant.INTEGER: { if (!omitCount) { appendInteger(count/1000, 1, 10, sb); } } break; case ECountVariant.INTEGER_CUSTOM: { int val = count / 1000; // only custom names we have for now if (unit == TimeUnit.MINUTE && (dr.fiveMinutes != null || dr.fifteenMinutes != null)) { if (val != 0 && val % 5 == 0) { if (dr.fifteenMinutes != null && (val == 15 || val == 45)) { val = val == 15 ? 1 : 3; if (!omitCount) appendInteger(val, 1, 10, sb); name = dr.fifteenMinutes; index = 8; // hack break; } if (dr.fiveMinutes != null) { val = val / 5; if (!omitCount) appendInteger(val, 1, 10, sb); name = dr.fiveMinutes; index = 9; // hack break; } } } if (!omitCount) appendInteger(val, 1, 10, sb); } break; case ECountVariant.HALF_FRACTION: { // 0, 1/2, 1, 1-1/2... int v = count / 500; if (v != 1) { if (!omitCount) appendCountValue(count, 1, 0, sb); } if ((v & 0x1) == 1) { // hack, using half name if (v == 1 && dr.halfNames != null && dr.halfNames[index] != null) { sb.append(name); return last ? index : -1; } int solox = v == 1 ? 0 : 1; if (dr.genders != null && dr.halves.length > 2) { if (dr.genders[index] == EGender.F) { solox += 2; } } int hp = dr.halfPlacements == null ? EHalfPlacement.PREFIX : dr.halfPlacements[solox & 0x1]; String half = dr.halves[solox]; String measure = dr.measures == null ? null : dr.measures[index]; switch (hp) { case EHalfPlacement.PREFIX: sb.append(half); break; case EHalfPlacement.AFTER_FIRST: { if (measure != null) { sb.append(measure); sb.append(half); if (useSep && !omitCount) { sb.append(dr.countSep); } sb.append(name); } else { // ignore sep completely sb.append(name); sb.append(half); return last ? index : -1; // might use suffix } } return -1; // exit early case EHalfPlacement.LAST: { if (measure != null) { sb.append(measure); } if (useSep && !omitCount) { sb.append(dr.countSep); } sb.append(name); sb.append(half); } return last ? index : -1; // might use suffix } } } break; default: { int decimals = 1; switch (cv) { case ECountVariant.DECIMAL2: decimals = 2; break; case ECountVariant.DECIMAL3: decimals = 3; break; default: break; } if (!omitCount) appendCountValue(count, 1, decimals, sb); } break; } if (!omitCount && useSep) { sb.append(dr.countSep); } if (!omitCount && dr.measures != null && index < dr.measures.length) { String measure = dr.measures[index]; if (measure != null) { sb.append(measure); } } sb.append(name); return last ? index : -1; } /** * Append a count value to the builder. * * @param count the count * @param integralDigits the number of integer digits to display * @param decimalDigits the number of decimal digits to display, <= 3 * @param sb the string builder to which to append the text */ public void appendCountValue(int count, int integralDigits, int decimalDigits, StringBuffer sb) { int ival = count / 1000; if (decimalDigits == 0) { appendInteger(ival, integralDigits, 10, sb); return; } if (dr.requiresDigitSeparator && sb.length() > 0) { sb.append(' '); } appendDigits(ival, integralDigits, 10, sb); int dval = count % 1000; if (decimalDigits == 1) { dval /= 100; } else if (decimalDigits == 2) { dval /= 10; } sb.append(dr.decimalSep); appendDigits(dval, decimalDigits, decimalDigits, sb); if (dr.requiresDigitSeparator) { sb.append(' '); } } public void appendInteger(int num, int mindigits, int maxdigits, StringBuffer sb) { if (dr.numberNames != null && num < dr.numberNames.length) { String name = dr.numberNames[num]; if (name != null) { sb.append(name); return; } } if (dr.requiresDigitSeparator && sb.length() > 0) { sb.append(' '); } switch (dr.numberSystem) { case ENumberSystem.DEFAULT: appendDigits(num, mindigits, maxdigits, sb); break; case ENumberSystem.CHINESE_TRADITIONAL: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.TRADITIONAL)); break; case ENumberSystem.CHINESE_SIMPLIFIED: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.SIMPLIFIED)); break; case ENumberSystem.KOREAN: sb.append( Utils.chineseNumber(num, Utils.ChineseDigits.KOREAN)); break; } if (dr.requiresDigitSeparator) { sb.append(' '); } } /** * Append digits to the string builder, using this.zero for '0' etc. * * @param num the integer to append * @param mindigits the minimum number of digits to append * @param maxdigits the maximum number of digits to append * @param sb the string builder to which to append the text */ public void appendDigits(long num, int mindigits, int maxdigits, StringBuffer sb) { char[] buf = new char[maxdigits]; int ix = maxdigits; while (ix > 0 && num > 0) { buf[--ix] = (char)(dr.zero + (num % 10)); num /= 10; } for (int e = maxdigits - mindigits; ix > e;) { buf[--ix] = dr.zero; } sb.append(buf, ix, maxdigits - ix); } /** * Append a marker for skipped units internal to a string. * @param sb the string builder to which to append the text */ public void appendSkippedUnit(StringBuffer sb) { if (dr.skippedUnitMarker != null) { sb.append(dr.skippedUnitMarker); } } /** * Append the appropriate separator between units * * @param unit the unit to which to append the separator * @param afterFirst true if this is the first unit formatted * @param beforeLast true if this is the next-to-last unit to be formatted * @param sb the string builder to which to append the text * @return true if a prefix will be required before a following unit */ public boolean appendUnitSeparator(TimeUnit unit, boolean longSep, boolean afterFirst, boolean beforeLast, StringBuffer sb) { // long seps // false, false "...b', '...d" // false, true "...', and 'c" // true, false - "a', '...c" // true, true - "a' and 'b" if ((longSep && dr.unitSep != null) || dr.shortUnitSep != null) { if (longSep && dr.unitSep != null) { int ix = (afterFirst ? 2 : 0) + (beforeLast ? 1 : 0); sb.append(dr.unitSep[ix]); return dr.unitSepRequiresDP != null && dr.unitSepRequiresDP[ix]; } sb.append(dr.shortUnitSep); // todo: investigate whether DP is required } return false; } private static final int FORM_PLURAL = 0, FORM_SINGULAR = 1, FORM_DUAL = 2, FORM_PAUCAL = 3, FORM_SINGULAR_SPELLED = 4, // following are not in the pluralization list FORM_SINGULAR_NO_OMIT = 5, // a hack FORM_HALF_SPELLED = 6; private int computeForm(TimeUnit unit, int count, int cv, boolean lastOfMultiple) { // first check if a particular form is forced by the countvariant. if // SO, just return that. otherwise convert the count to an integer // and use pluralization rules to determine which form to use. // careful, can't assume any forms but plural exist. if (trace) { System.err.println("pfd.cf unit: " + unit + " count: " + count + " cv: " + cv + " dr.pl: " + dr.pl); Thread.dumpStack(); } if (dr.pl == EPluralization.NONE) { return FORM_PLURAL; } // otherwise, assume we have at least a singular and plural form int val = count/1000; switch (cv) { case ECountVariant.INTEGER: case ECountVariant.INTEGER_CUSTOM: { // do more analysis based on floor of count } break; case ECountVariant.HALF_FRACTION: { switch (dr.fractionHandling) { case EFractionHandling.FPLURAL: return FORM_PLURAL; case EFractionHandling.FSINGULAR_PLURAL_ANDAHALF: case EFractionHandling.FSINGULAR_PLURAL: { // if half-floor is 1/2, use singular // else if half-floor is not integral, use plural // else do more analysis int v = count / 500; if (v == 1) { if (dr.halfNames != null && dr.halfNames[unit.ordinal()] != null) { return FORM_HALF_SPELLED; } return FORM_SINGULAR_NO_OMIT; } if ((v & 0x1) == 1) { if (dr.pl == EPluralization.ARABIC && v > 21) { // hack return FORM_SINGULAR_NO_OMIT; } if (v == 3 && dr.pl == EPluralization.PLURAL && dr.fractionHandling != EFractionHandling.FSINGULAR_PLURAL_ANDAHALF) { return FORM_PLURAL; } } // it will display like an integer, so do more analysis } break; case EFractionHandling.FPAUCAL: { int v = count / 500; if (v == 1 || v == 3) { return FORM_PAUCAL; } // else use integral form } break; default: throw new IllegalStateException(); } } break; default: { // for all decimals switch (dr.decimalHandling) { case EDecimalHandling.DPLURAL: break; case EDecimalHandling.DSINGULAR: return FORM_SINGULAR_NO_OMIT; case EDecimalHandling.DSINGULAR_SUBONE: if (count < 1000) { return FORM_SINGULAR_NO_OMIT; } break; case EDecimalHandling.DPAUCAL: if (dr.pl == EPluralization.PAUCAL) { return FORM_PAUCAL; } break; default: break; } return FORM_PLURAL; } } // select among pluralization forms if (trace && count == 0) { System.err.println("EZeroHandling = " + dr.zeroHandling); } if (count == 0 && dr.zeroHandling == EZeroHandling.ZSINGULAR) { return FORM_SINGULAR_SPELLED; } int form = FORM_PLURAL; switch(dr.pl) { case EPluralization.NONE: break; // never get here case EPluralization.PLURAL: { if (val == 1) { form = FORM_SINGULAR_SPELLED; // defaults to form_singular if no spelled forms } } break; case EPluralization.DUAL: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { form = FORM_SINGULAR; } } break; case EPluralization.PAUCAL: { int v = val; v = v % 100; if (v > 20) { v = v % 10; } if (v == 1) { form = FORM_SINGULAR; } else if (v > 1 && v < 5) { form = FORM_PAUCAL; } } break; /* case EPluralization.RPT_DUAL_FEW: { int v = val; if (v > 20) { v = v % 10; } if (v == 1) { form = FORM_SINGULAR; } else if (v == 2) { form = FORM_DUAL; } else if (v > 2 && v < 5) { form = FORM_PAUCAL; } } break; */ case EPluralization.HEBREW: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { if (lastOfMultiple) { form = FORM_SINGULAR_SPELLED; } else { form = FORM_SINGULAR; } } else if (unit == TimeUnit.YEAR && val > 11) { form = FORM_SINGULAR_NO_OMIT; } } break; case EPluralization.ARABIC: { if (val == 2) { form = FORM_DUAL; } else if (val == 1) { form = FORM_SINGULAR; } else if (val > 10) { form = FORM_SINGULAR_NO_OMIT; } } break; default: System.err.println("dr.pl is " + dr.pl); throw new IllegalStateException(); } return form; } }
blob \n1. long method\n2. data class t t f {"\\",n,1,.," ",l,o,n,g," ",m,e,t,h,o,d,"\\",n,2,.," ",d,a,t,a," ",c,l,a,s,s} {"\\",n,1,.," ",o,n,g," ",m,t,h,o,d,"\\",n,2,.," ",d,t," ",c} 0 6926 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/duration/impl/PeriodFormatterData.java/#L37-L676 1 3452 6926
831 {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } }
blob long method, data class t t f long method, data class blob 0 7738 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 1 831 7738
1586    { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl
blob Data Class t f f Data Class blob 0 11369 https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 1 1586 11369
728   { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; }
feature envy long method, data class t t f long method, data class feature envy 0 6853 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 1 728 6853
694 {"response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 6656 https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 1 694 6656
1228 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; }
feature envy long method, data class t t f long method, data class feature envy 0 10354 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 1 1228 10354
756 { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class, 3. Blob" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; }
long method 1. long method, 2. data class, 3. blob t t t  2. data class, 3. blob   0 7049 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 1 756 7049
1862      { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@NbBundle.Messages({ "LocksFeatureUI_show=View by:", "LocksFeatureUI_aggregationByThreads=Threads", "LocksFeatureUI_aggregationByMonitors=Monitors", "LocksFeatureUI_aggregationHint=Results aggregation" }) abstract class LocksFeatureUI extends FeatureUI { private ProfilerToolbar toolbar; private LockContentionPanel locksView; // --- External implementation --------------------------------------------- abstract ProfilerClient getProfilerClient(); abstract void refreshResults(); // --- API implementation -------------------------------------------------- ProfilerToolbar getToolbar() { if (toolbar == null) initUI(); return toolbar; } JPanel getResultsUI() { if (locksView == null) initUI(); return locksView; } void sessionStateChanged(int sessionState) { refreshToolbar(sessionState); if (sessionState == Profiler.PROFILING_INACTIVE || sessionState == Profiler.PROFILING_IN_TRANSITION) { if (locksView != null) locksView.profilingSessionFinished(); } else if (sessionState == Profiler.PROFILING_RUNNING) { if (locksView != null) locksView.profilingSessionStarted(); } } void resetPause() { // if (lrPauseButton != null) lrPauseButton.setSelected(false); } void setForceRefresh() { if (locksView != null) locksView.setForceRefresh(true); } void refreshData() throws ClientUtils.TargetAppOrVMTerminated { if (locksView != null) locksView.refreshData(); } void resetData() { if (locksView != null) locksView.resetData(); } // --- UI ------------------------------------------------------------------ private JLabel shLabel; private ActionPopupButton shAggregation; private void initUI() { assert SwingUtilities.isEventDispatchThread(); // --- Results --------------------------------------------------------- locksView = new LockContentionPanel() { protected ProfilerClient getProfilerClient() { return LocksFeatureUI.this.getProfilerClient(); } }; locksView.lockContentionEnabled(); locksView.putClientProperty("HelpCtx.Key", "ProfileLocks.HelpCtx"); // NOI18N // --- Toolbar --------------------------------------------------------- shLabel = new GrayLabel(Bundle.LocksFeatureUI_show()); Action aThreads = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByThreads()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_THREADS); } }; Action aMonitors = new AbstractAction() { { putValue(NAME, Bundle.LocksFeatureUI_aggregationByMonitors()); } public void actionPerformed(ActionEvent e) { setAggregation(LockContentionPanel.Aggregation.BY_MONITORS); } }; shAggregation = new ActionPopupButton(aThreads, aMonitors); shAggregation.setToolTipText(Bundle.LocksFeatureUI_aggregationHint()); toolbar = ProfilerToolbar.create(true); toolbar.addSpace(2); toolbar.addSeparator(); toolbar.addSpace(5); toolbar.add(shLabel); toolbar.addSpace(2); toolbar.add(shAggregation); // --- Sync UI --------------------------------------------------------- setAggregation(LockContentionPanel.Aggregation.BY_THREADS); sessionStateChanged(getSessionState()); } private void refreshToolbar(final int state) { // if (toolbar != null) SwingUtilities.invokeLater(new Runnable() { // public void run() { // } // }); } private void setAggregation(LockContentionPanel.Aggregation aggregation) { locksView.setAggregation(aggregation); shAggregation.selectAction(aggregation.ordinal()); } }
blob data class, long method t t f data class, long method blob 0 12224 https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler/src/org/graalvm/visualvm/lib/profiler/v2/features/LocksFeatureUI.java/#L65-L192 1 1862 12224
1726 {"response": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CoordActionQueryExecutor extends QueryExecutor { public enum CoordActionQuery { UPDATE_COORD_ACTION, UPDATE_COORD_ACTION_STATUS_PENDING_TIME, UPDATE_COORD_ACTION_FOR_INPUTCHECK, UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK, UPDATE_COORD_ACTION_DEPENDENCIES, UPDATE_COORD_ACTION_FOR_START, UPDATE_COORD_ACTION_FOR_MODIFIED_DATE, UPDATE_COORD_ACTION_RERUN, GET_COORD_ACTION, GET_COORD_ACTION_STATUS, GET_COORD_ACTIVE_ACTIONS_COUNT_BY_JOBID, GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME, GET_COORD_ACTIONS_STATUS_UNIGNORED, GET_COORD_ACTIONS_PENDING_COUNT, GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE, GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE, GET_TERMINATED_ACTIONS_FOR_DATES, GET_TERMINATED_ACTION_IDS_FOR_DATES, GET_ACTIVE_ACTIONS_FOR_DATES, GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN, GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN, GET_COORD_ACTION_FOR_SLA, GET_COORD_ACTION_FOR_INPUTCHECK }; private static CoordActionQueryExecutor instance = new CoordActionQueryExecutor(); private CoordActionQueryExecutor() { } public static QueryExecutor getInstance() { return CoordActionQueryExecutor.instance; } @Override public Query getUpdateQuery(CoordActionQuery namedQuery, CoordinatorActionBean actionBean, EntityManager em) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); switch (namedQuery) { case UPDATE_COORD_ACTION: query.setParameter("actionNumber", actionBean.getActionNumber()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("consoleUrl", actionBean.getConsoleUrl()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("timeOut", actionBean.getTimeOut()); query.setParameter("trackerUri", actionBean.getTrackerUri()); query.setParameter("type", actionBean.getType()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("jobId", actionBean.getJobId()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("nominalTime", actionBean.getNominalTimestamp()); query.setParameter("slaXml", actionBean.getSlaXmlBlob()); query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_STATUS_PENDING_TIME: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("pending", actionBean.getPending()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_PUSH_INPUTCHECK: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_DEPENDENCIES: query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_START: query.setParameter("status", actionBean.getStatus().toString()); query.setParameter("lastModifiedTime", new Date()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("pending", actionBean.getPending()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_FOR_MODIFIED_DATE: query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("id", actionBean.getId()); break; case UPDATE_COORD_ACTION_RERUN: query.setParameter("actionXml", actionBean.getActionXmlBlob()); query.setParameter("status", actionBean.getStatusStr()); query.setParameter("externalId", actionBean.getExternalId()); query.setParameter("externalStatus", actionBean.getExternalStatus()); query.setParameter("rerunTime", actionBean.getRerunTimestamp()); query.setParameter("lastModifiedTime", actionBean.getLastModifiedTimestamp()); query.setParameter("createdTime", actionBean.getCreatedTimestamp()); query.setParameter("createdConf", actionBean.getCreatedConfBlob()); query.setParameter("runConf", actionBean.getRunConfBlob()); query.setParameter("missingDependencies", actionBean.getMissingDependenciesBlob()); query.setParameter("pushMissingDependencies", actionBean.getPushMissingDependenciesBlob()); query.setParameter("errorCode", actionBean.getErrorCode()); query.setParameter("errorMessage", actionBean.getErrorMessage()); query.setParameter("id", actionBean.getId()); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + namedQuery.name()); } return query; } @Override public Query getSelectQuery(CoordActionQuery namedQuery, EntityManager em, Object... parameters) throws JPAExecutorException { Query query = em.createNamedQuery(namedQuery.name()); CoordActionQuery caQuery = (CoordActionQuery) namedQuery; switch (caQuery) { case GET_COORD_ACTION: case GET_COORD_ACTION_STATUS: case GET_COORD_ACTION_FOR_SLA: case GET_COORD_ACTION_FOR_INPUTCHECK: query.setParameter("id", parameters[0]); break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: query.setParameter("jobId", parameters[0]); break; case GET_COORD_ACTIONS_PENDING_COUNT: query.setParameter("jobId", parameters[0]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: query.setParameter("ids", parameters[0]); break; case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: query.setParameter("jobId", parameters[0]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: case GET_TERMINATED_ACTION_IDS_FOR_DATES: case GET_ACTIVE_ACTIONS_FOR_DATES: query.setParameter("jobId", parameters[0]); query.setParameter("startTime", new Timestamp(((Date) parameters[1]).getTime())); query.setParameter("endTime", new Timestamp(((Date) parameters[2]).getTime())); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: query.setParameter("lastModifiedTime", new Timestamp(((Date) parameters[0]).getTime())); query.setParameter("currentTime", new Timestamp(new Date().getTime())); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot set parameters for " + caQuery.name()); } return query; } @Override public int executeUpdate(CoordActionQuery namedQuery, CoordinatorActionBean jobBean) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getUpdateQuery(namedQuery, jobBean, em); int ret = jpaService.executeUpdate(namedQuery.name(), query, em); return ret; } @Override public CoordinatorActionBean get(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { CoordinatorActionBean bean = getIfExist(namedQuery, parameters); if (bean == null) { throw new JPAExecutorException(ErrorCode.E0605, getSelectQuery(namedQuery, Services.get().get(JPAService.class).getEntityManager(), parameters).toString()); } return bean; } @Override public CoordinatorActionBean getIfExist(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { return null; } CoordinatorActionBean bean = constructBean(namedQuery, ret); return bean; } @Override public List getList(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); List retList = (List) jpaService.executeGetList(namedQuery.name(), query, em); List beanList = new ArrayList(); if (retList != null) { for (Object ret : retList) { beanList.add(constructBean(namedQuery, ret)); } } return beanList; } private CoordinatorActionBean constructBean(CoordActionQuery namedQuery, Object ret) throws JPAExecutorException { CoordinatorActionBean bean; Object[] arr; switch (namedQuery) { case GET_COORD_ACTION: bean = (CoordinatorActionBean) ret; break; case GET_COORD_ACTIONS_BY_LAST_MODIFIED_TIME: bean = new CoordinatorActionBean(); bean.setJobId((String) ret); break; case GET_COORD_ACTION_STATUS: bean = new CoordinatorActionBean(); bean.setStatusStr((String)ret); break; case GET_COORD_ACTIONS_STATUS_UNIGNORED: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setStatusStr((String)arr[0]); bean.setPending((Integer)arr[1]); break; case GET_ACTIVE_ACTIONS_IDS_FOR_SLA_CHANGE: case GET_ACTIVE_ACTIONS_JOBID_FOR_SLA_CHANGE: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setNominalTime((Timestamp)arr[1]); bean.setCreatedTime((Timestamp)arr[2]); bean.setActionXmlBlob((StringBlob)arr[3]); break; case GET_TERMINATED_ACTIONS_FOR_DATES: bean = (CoordinatorActionBean) ret; break; case GET_TERMINATED_ACTION_IDS_FOR_DATES: bean = new CoordinatorActionBean(); bean.setId((String) ret); break; case GET_ACTIVE_ACTIONS_FOR_DATES: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); bean.setNominalTime((Timestamp) arr[5]); bean.setCreatedTime((Timestamp) arr[6]); break; case GET_COORD_ACTIONS_FOR_RECOVERY_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPending((Integer) arr[4]); break; case GET_COORD_ACTIONS_WAITING_READY_SUBMITTED_OLDER_THAN: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String)arr[0]); bean.setJobId((String)arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setPushMissingDependenciesBlob((StringBlob) arr[4]); break; case GET_COORD_ACTION_FOR_SLA: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setJobId((String) arr[1]); bean.setStatusStr((String) arr[2]); bean.setExternalId((String) arr[3]); bean.setLastModifiedTime((Timestamp) arr[4]); break; case GET_COORD_ACTION_FOR_INPUTCHECK: arr = (Object[]) ret; bean = new CoordinatorActionBean(); bean.setId((String) arr[0]); bean.setActionNumber((Integer) arr[1]); bean.setJobId((String) arr[2]); bean.setStatus(CoordinatorAction.Status.valueOf((String) arr[3])); bean.setRunConfBlob((StringBlob) arr[4]); bean.setNominalTime(DateUtils.toDate((Timestamp) arr[5])); bean.setCreatedTime(DateUtils.toDate((Timestamp) arr[6])); bean.setActionXmlBlob((StringBlob) arr[7]); bean.setMissingDependenciesBlob((StringBlob) arr[8]); bean.setPushMissingDependenciesBlob((StringBlob) arr[9]); bean.setTimeOut((Integer) arr[10]); bean.setExternalId((String) arr[11]); break; default: throw new JPAExecutorException(ErrorCode.E0603, "QueryExecutor cannot construct action bean for " + namedQuery.name()); } return bean; } @Override public Object getSingleValue(CoordActionQuery namedQuery, Object... parameters) throws JPAExecutorException { JPAService jpaService = Services.get().get(JPAService.class); EntityManager em = jpaService.getEntityManager(); Query query = getSelectQuery(namedQuery, em, parameters); Object ret = jpaService.executeGet(namedQuery.name(), query, em); if (ret == null) { throw new JPAExecutorException(ErrorCode.E0604, query.toString()); } return ret; } }
blob data class t t f data class blob 0 11808 https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/executor/jpa/CoordActionQueryExecutor.java/#L40-L383 1 1726 11808
5040 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } }
blob data class, long method t t f data class, long method blob 0 14066 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 1 5040 14066
1433  { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = CreateZoneDetails.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class CreateZoneDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("zoneType") private ZoneType zoneType; public Builder zoneType(ZoneType zoneType) { this.zoneType = zoneType; this.__explicitlySet__.add("zoneType"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") private String compartmentId; public Builder compartmentId(String compartmentId) { this.compartmentId = compartmentId; this.__explicitlySet__.add("compartmentId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") private java.util.Map freeformTags; public Builder freeformTags(java.util.Map freeformTags) { this.freeformTags = freeformTags; this.__explicitlySet__.add("freeformTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("definedTags") private java.util.Map> definedTags; public Builder definedTags( java.util.Map> definedTags) { this.definedTags = definedTags; this.__explicitlySet__.add("definedTags"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") private java.util.List externalMasters; public Builder externalMasters(java.util.List externalMasters) { this.externalMasters = externalMasters; this.__explicitlySet__.add("externalMasters"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); public CreateZoneDetails build() { CreateZoneDetails __instance__ = new CreateZoneDetails( name, zoneType, compartmentId, freeformTags, definedTags, externalMasters); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(CreateZoneDetails o) { Builder copiedBuilder = name(o.getName()) .zoneType(o.getZoneType()) .compartmentId(o.getCompartmentId()) .freeformTags(o.getFreeformTags()) .definedTags(o.getDefinedTags()) .externalMasters(o.getExternalMasters()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The name of the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ public enum ZoneType { Primary("PRIMARY"), Secondary("SECONDARY"), ; private final String value; private static java.util.Map map; static { map = new java.util.HashMap<>(); for (ZoneType v : ZoneType.values()) { map.put(v.getValue(), v); } } ZoneType(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static ZoneType create(String key) { if (map.containsKey(key)) { return map.get(key); } throw new RuntimeException("Invalid ZoneType: " + key); } }; /** * The type of the zone. Must be either `PRIMARY` or `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("zoneType") ZoneType zoneType; /** * The OCID of the compartment containing the zone. **/ @com.fasterxml.jackson.annotation.JsonProperty("compartmentId") String compartmentId; /** * Simple key-value pair that is applied without any predefined name, type, or scope. * For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). * Example: `{\"bar-key\": \"value\"}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("freeformTags") java.util.Map freeformTags; /** * Usage of predefined tag keys. These predefined keys are scoped to a namespace. * Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` * **/ @com.fasterxml.jackson.annotation.JsonProperty("definedTags") java.util.Map> definedTags; /** * External master servers for the zone. `externalMasters` becomes a * required parameter when the `zoneType` value is `SECONDARY`. * **/ @com.fasterxml.jackson.annotation.JsonProperty("externalMasters") java.util.List externalMasters; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set __explicitlySet__ = new java.util.HashSet(); }
blob data class t t f data class blob 0 10958 https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-dns/src/main/java/com/oracle/bmc/dns/model/CreateZoneDetails.java/#L19-L204 1 1433 10958
2668   YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Large class 4. Long parameter list 5. Data class 6. Data clump 7. Lazy class 8. Message chains 9. Primitive obsession 10. Duplicate code 11. Magic numbers 12. Shotgun surgery 13. Inconsistent variable naming 14. Unused imports 15. Unnecessary comments 16. Inconsistent use of whitespace 17. Unnecessary injection 18. Poor exception handling. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } }
blob  Long method2 Feature envy3 Large class4 Long parameter list5 Data class6 Data clump7 Lazy class8 Message chains9 Primitive obsession t f f . Long method2. Feature envy3. Large class4. Long parameter list5. Data class6. Data clump7. Lazy class8. Message chains9. Primitive obsession blob 0 15207 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 2 2668 15207
1954 { "output": "YES I found bad smells\nthe bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 12540 https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 1 1954 12540
2123 {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } }
blob data class, long method t t f data class, long method blob 0 13215 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 1 2123 13215
4558  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class StubConfiguration extends AbstractConfiguration { private static final Logger LOG = LoggerFactory.getLogger(StubConfiguration.class); private static final String STATUS_GETTER_URL_POSTFIX = "config/public/stubdescriptor"; private static final String STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changestatus"; private static final String STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX = "config/admin/stub/changeorder"; private static final String DROP_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/drop"; private static final String SAVE_STUB_CONFIG_URL_POSTFIX = "config/admin/stub/save"; private static final String GROUP_NAME = "groupname"; private static final String DIRECTION = "direction"; private static final String NEXT_STATUS = "nextstatus"; /** * Constructor. * * @param config the Wilma server configuration */ public StubConfiguration(WilmaServiceConfig config) { super(config); } /** * Constructor. * * @param config the Wilma server configuration * @param client the Wilma HTTP client */ public StubConfiguration(WilmaServiceConfig config, WilmaHttpClient client) { super(config, client); } /** * Gets the stub configuration information. * * @return stub configuration information in JSONObject */ public JSONObject getStubConfigInformation() { LOG.debug("Call stub configuration API."); return getterRequest(STATUS_GETTER_URL_POSTFIX); } /** * Sets the status of the given stub group. * * @param groupName the name of the stub group * @param status the new status * @return true if the request is successful, otherwise return false */ public boolean setStubConfigStatus(String groupName, StubConfigStatus status) { LOG.debug("Call stub status setter API with value: {}, for group: {}", status, groupName); return setterRequest(STUB_CONFIG_STATUS_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, NEXT_STATUS, Boolean.toString(status.getNextStatus()))); } /** * Sets the new order of the given stub group. * * @param groupName the name of the stub group * @param order the new order * @return true if the request is successful, otherwise return false */ public boolean setStubConfigOrder(String groupName, StubConfigOrder order) { LOG.debug("Call stub order setter API with value: {}, for group: {}", order, groupName); return setterRequest(STUB_CONFIG_ORDER_CHANGE_SETTER_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName, DIRECTION, Integer.toString(order.getDirection()))); } /** * Drops the given stub group configuration. * * @param groupName the name of the stub group * @return true if the request is successful, otherwise return false */ public boolean dropStubConfig(String groupName) { LOG.debug("Call drop stub configuration API for group: {}", groupName); return setterRequest(DROP_STUB_CONFIG_URL_POSTFIX, ImmutableMap.of(GROUP_NAME, groupName)); } /** * Drops the all stub configuration. * Whichever drop try was unsuccessful then return {@code false} but try to * drop the others. The supposed stub configuration information JSON format * is the following: * * { * "configs": [ * { * "sequenceDescriptors": [ { ... } ], * "dialogDescriptors": [ { ... } ], * "groupname": "Default", * "active": "true" * } * ] * } * * * @return true if all the stub configuration is dropped * successfully (or was empty and nothing to be dropped), otherwise return false */ public boolean dropAllStubConfig() { LOG.debug("Call drop all stub configuration."); boolean droppedAllStubConfig = true; JSONObject stubConfig = getStubConfigInformation(); if ((stubConfig != null) && (stubConfig.length() > 0)) { try { LOG.debug("Gets stub configs array from all stub configuration JSON."); JSONArray configs = stubConfig.getJSONArray("configs"); for (int i = 0; i < configs.length(); i++) { LOG.debug("Get the stub group name."); String groupName = configs.getJSONObject(i).getString("groupname"); droppedAllStubConfig &= dropStubConfig(groupName); LOG.info("Dropped stub configuration: {}", groupName); } } catch (JSONException e) { LOG.error("Error occurred while dropping sub configuration. ", e); droppedAllStubConfig = false; } } else { droppedAllStubConfig = false; } return droppedAllStubConfig; } /** * Save the actual stub configuration. * * @return true if the request is successful, otherwise return false */ public boolean persistActualStubConfig() { LOG.debug("Call save stub configuration API."); return setterRequest(SAVE_STUB_CONFIG_URL_POSTFIX); } }
blob data class t t f data class blob 0 12116 https://github.com/epam/Wilma/blob/af271176f7847d06512b62ed8f1a4a0e7fd8b10a/wilma-service-api/src/main/java/com/epam/wilma/service/configuration/StubConfiguration.java/#L38-L178 1 4558 12116
1600  {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class WebServer { public static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private HttpServer2 httpServer; private final HasConfig conf; private InetSocketAddress httpAddress; private InetSocketAddress httpsAddress; protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver"; public WebServer(HasConfig conf) { this.conf = conf; } public HasConfig getConf() { return conf; } private void init() { final String pathSpec = "/has/v1/*"; // add has packages httpServer.addJerseyResourcePackage(AsRequestApi.class .getPackage().getName(), pathSpec); } public void defineFilter() { String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType.equals("kerberos")) { // add authentication filter for webhdfs final String className = conf.getString( WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY, WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT); final String name = className; Map params = getAuthFilterParams(conf); String kadminPathSpec = "/has/v1/kadmin/*"; String hadminPathSpec = "/has/v1/hadmin/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className, params, new String[]{kadminPathSpec, hadminPathSpec}); HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className + ")"); } } public void defineConfFilter() { String confFilterName = ConfFilter.class.getName(); String confPath = "/has/v1/conf/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName, getAuthFilterParams(conf), new String[]{confPath}); HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName + ")"); } private Map getAuthFilterParams(HasConfig conf) { Map params = new HashMap<>(); String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType != null && !authType.isEmpty()) { params.put(AuthenticationFilter.AUTH_TYPE, authType); } String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY); if (principal != null && !principal.isEmpty()) { try { principal = SecurityUtil.getServerPrincipal(principal, getHttpsAddress().getHostName()); } catch (IOException e) { LOG.warn("Errors occurred when get server principal. " + e.getMessage()); } params.put(KerberosAuthenticationHandler.PRINCIPAL, principal); } String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY); if (keytab != null && !keytab.isEmpty()) { params.put(KerberosAuthenticationHandler.KEYTAB, keytab); } String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES); if (rule != null && !rule.isEmpty()) { params.put(KerberosAuthenticationHandler.NAME_RULES, rule); } else { params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT"); } return params; } public InetSocketAddress getBindAddress() { if (httpAddress != null) { return httpAddress; } else if (httpsAddress != null) { return httpsAddress; } else { return null; } } /** * for information related to the different configuration options and * Http Policy is decided. * * @throws HasException HAS exception when starting web server */ public void start() throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); final String bindHost = conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY); InetSocketAddress httpAddr = null; if (policy.isHttpEnabled()) { final String httpAddrString = conf.getString( WebConfigKey.HAS_HTTP_ADDRESS_KEY, WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT); httpAddr = NetUtils.createSocketAddr(httpAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort()); } LOG.info("Get the http address: " + httpAddr); } InetSocketAddress httpsAddr = null; if (policy.isHttpsEnabled()) { final String httpsAddrString = conf.getString( WebConfigKey.HAS_HTTPS_ADDRESS_KEY, WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT); httpsAddr = NetUtils.createSocketAddr(httpsAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort()); } LOG.info("Get the https address: " + httpsAddr); } HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has"); try { httpServer = builder.build(); } catch (IOException e) { throw new HasException("Errors occurred when building http server. " + e.getMessage()); } init(); try { httpServer.start(); } catch (IOException e) { throw new HasException("Errors occurred when starting http server. " + e.getMessage()); } int connIdx = 0; if (policy.isHttpEnabled()) { httpAddress = httpServer.getConnectorAddress(connIdx++); if (httpAddress != null) { conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, NetUtils.getHostPortString(httpAddress)); } } if (policy.isHttpsEnabled()) { httpsAddress = httpServer.getConnectorAddress(connIdx); if (httpsAddress != null) { conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, NetUtils.getHostPortString(httpsAddress)); } } } public void setWebServerAttribute(HasServer hasServer) { httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer); } public static HasServer getHasServerFromContext(ServletContext context) { return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY); } /** * Get http policy. * * @param conf the HAS config * @return HttpConfig.Policy the policy */ public HttpConfig.Policy getHttpPolicy(HasConfig conf) { String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY, WebConfigKey.HAS_HTTP_POLICY_DEFAULT); HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr); if (policy == null) { throw new HadoopIllegalArgumentException("Unrecognized value '" + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY); } conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name()); return policy; } /** * Return a HttpServer.Builder that the HAS can use to * initialize their HTTP / HTTPS server. * * @param conf the HAS config * @param httpAddr the InetSocketAddress of http * @param httpsAddr the InetSocketAddress of https * @param name the host name * @return HttpServer2.Builder the builder * @throws HasException HAS exception */ public HttpServer2.Builder httpServerTemplateForHAS( HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name) throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); HttpServer2.Builder builder = new HttpServer2.Builder().setName(name); if (policy.isHttpEnabled()) { if (httpAddr != null && httpAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } if (policy.isHttpsEnabled() && httpsAddr != null) { HasConfig sslConf = loadSslConfiguration(conf); loadSslConfToHttpServerBuilder(builder, sslConf); if (httpsAddr != null && httpsAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } return builder; } /** * Load HTTPS-related configuration. * * @param conf HAS config * @return HasConfig after loading ssl configuration * @throws HasException HAS exception when loading HTTPS related configuration */ public HasConfig loadSslConfiguration(HasConfig conf) throws HasException { HasConfig sslConf = new HasConfig(); String sslConfigString = conf.getString( WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT); LOG.info("Get the ssl config file: " + sslConfigString); File sslConfig = new File(sslConfigString); if (!sslConfig.exists()) { throw new HasException("The ssl server config file " + sslConfigString + " does not exist."); } try { sslConf.addIniConfig(sslConfig); } catch (IOException e) { throw new HasException("Errors occurred when adding config. " + e.getMessage()); } final String[] reqSslProps = { WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY }; // Check if the required properties are included for (String sslProp : reqSslProps) { if (sslConf.getString(sslProp) == null) { LOG.warn("SSL config " + sslProp + " is missing. If " + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY + " is specified, make sure it is a relative path"); } } boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT); sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth); return sslConf; } public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder, HasConfig sslConf) { return builder .needsClientAuth( sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT)) .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY)) .keyStore(sslConf.getString("ssl.server.keystore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.keystore.type", "jks")) .trustStore(sslConf.getString("ssl.server.truststore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.truststore.type", "jks")) .excludeCiphers( sslConf.getString("ssl.server.exclude.cipher.list")); } /** * Leverages the Configuration.getPassword method to attempt to get * passwords from the CredentialProvider API before falling back to * clear text in config - if falling back is allowed. * * @param conf Configuration instance * @param alias name of the credential to retreive * @return String credential value or null */ public String getPassword(HasConfig conf, String alias) { return conf.getString(alias); } public void stop() throws Exception { if (httpServer != null) { httpServer.stop(); } } public InetSocketAddress getHttpAddress() { return httpAddress; } public InetSocketAddress getHttpsAddress() { return httpsAddress; } }
blob Long Method, Blob, Data Class t f t Long Method, Data Class   0 11427 https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java/#L43-L374 1 1600 11427
1622      { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11487 https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 1 1622 11487
4239  {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); }
long method long method, data class t t t  data class   0 11159 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 1 4239 11159
248  { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Service public class DepositAccountAssembler { private final PlatformSecurityContext context; private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsHelper savingsHelper; private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final StaffRepositoryWrapper staffRepository; private final FixedDepositProductRepository fixedDepositProductRepository; private final RecurringDepositProductRepository recurringDepositProductRepository; private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final SavingsAccountChargeAssembler savingsAccountChargeAssembler; private final FromJsonHelper fromApiJsonHelper; private final DepositProductAssembler depositProductAssembler; private final PaymentDetailAssembler paymentDetailAssembler; @Autowired public DepositAccountAssembler(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final ClientRepositoryWrapper clientRepository, final GroupRepositoryWrapper groupRepository, final StaffRepositoryWrapper staffRepository, final FixedDepositProductRepository fixedDepositProductRepository, final SavingsAccountRepositoryWrapper savingsAccountRepository, final SavingsAccountChargeAssembler savingsAccountChargeAssembler, final FromJsonHelper fromApiJsonHelper, final DepositProductAssembler depositProductAssembler, final RecurringDepositProductRepository recurringDepositProductRepository, final AccountTransfersReadPlatformService accountTransfersReadPlatformService, final PlatformSecurityContext context, final PaymentDetailAssembler paymentDetailAssembler) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.staffRepository = staffRepository; this.fixedDepositProductRepository = fixedDepositProductRepository; this.savingsAccountRepository = savingsAccountRepository; this.savingsAccountChargeAssembler = savingsAccountChargeAssembler; this.fromApiJsonHelper = fromApiJsonHelper; this.depositProductAssembler = depositProductAssembler; this.recurringDepositProductRepository = recurringDepositProductRepository; this.savingsHelper = new SavingsHelper(accountTransfersReadPlatformService); this.context = context; this.paymentDetailAssembler = paymentDetailAssembler; } /** * Assembles a new {@link SavingsAccount} from JSON details passed in * request inheriting details where relevant from chosen * {@link SavingsProduct}. */ public SavingsAccount assembleFrom(final JsonCommand command, final AppUser submittedBy, final DepositAccountType depositAccountType) { final JsonElement element = command.parsedJson(); final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); SavingsProduct product = null; if (depositAccountType.isFixedDeposit()) { product = this.fixedDepositProductRepository.findOne(productId); if (product == null) { throw new FixedDepositProductNotFoundException(productId); } } else if (depositAccountType.isRecurringDeposit()) { product = this.recurringDepositProductRepository.findOne(productId); if (product == null) { throw new RecurringDepositProductNotFoundException(productId); } } if (product == null) { throw new SavingsProductNotFoundException(productId); } Client client = null; Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; } if (group != null && client != null) { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } accountType = AccountType.JLG; if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); } else { interestRate = product.nominalAnnualInterestRate(); } SavingsCompoundingInterestPeriodType interestCompoundingPeriodType = null; final Integer interestPeriodTypeValue = command.integerValueOfParameterNamed(interestCompoundingPeriodTypeParamName); if (interestPeriodTypeValue != null) { interestCompoundingPeriodType = SavingsCompoundingInterestPeriodType.fromInt(interestPeriodTypeValue); } else { interestCompoundingPeriodType = product.interestCompoundingPeriodType(); } SavingsPostingInterestPeriodType interestPostingPeriodType = null; final Integer interestPostingPeriodTypeValue = command.integerValueOfParameterNamed(interestPostingPeriodTypeParamName); if (interestPostingPeriodTypeValue != null) { interestPostingPeriodType = SavingsPostingInterestPeriodType.fromInt(interestPostingPeriodTypeValue); } else { interestPostingPeriodType = product.interestPostingPeriodType(); } SavingsInterestCalculationType interestCalculationType = null; final Integer interestCalculationTypeValue = command.integerValueOfParameterNamed(interestCalculationTypeParamName); if (interestCalculationTypeValue != null) { interestCalculationType = SavingsInterestCalculationType.fromInt(interestCalculationTypeValue); } else { interestCalculationType = product.interestCalculationType(); } SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = command .integerValueOfParameterNamed(interestCalculationDaysInYearTypeParamName); if (interestCalculationDaysInYearTypeValue != null) { interestCalculationDaysInYearType = SavingsInterestCalculationDaysInYearType.fromInt(interestCalculationDaysInYearTypeValue); } else { interestCalculationDaysInYearType = product.interestCalculationDaysInYearType(); } BigDecimal minRequiredOpeningBalance = null; if (command.parameterExists(minRequiredOpeningBalanceParamName)) { minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); } else { minRequiredOpeningBalance = product.minRequiredOpeningBalance(); } Integer lockinPeriodFrequency = null; if (command.parameterExists(lockinPeriodFrequencyParamName)) { lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); } else { lockinPeriodFrequency = product.lockinPeriodFrequency(); } SavingsPeriodFrequencyType lockinPeriodFrequencyType = null; if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { Integer lockinPeriodFrequencyTypeValue = null; lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); if (lockinPeriodFrequencyTypeValue != null) { lockinPeriodFrequencyType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); } } else { lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); } boolean iswithdrawalFeeApplicableForTransfer = false; if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element, product.currency().getCode()); DepositAccountInterestRateChart accountChart = null; InterestRateChart productChart = null; if (command.parameterExists(chartIdParamName)) { Long chartId = command.longValueOfParameterNamed(chartIdParamName); productChart = product.findChart(chartId); } else { productChart = product.applicableChart(submittedOnDate); } if (productChart != null) { accountChart = DepositAccountInterestRateChart.from(productChart); } boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); if(withHoldTax && product.getTaxGroup() == null){ throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } SavingsAccount account = null; if (depositAccountType.isFixedDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((FixedDepositProduct) product).depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); FixedDepositAccount fdAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(fdAccount); fdAccount.validateDomainRules(); account = fdAccount; } else if (depositAccountType.isRecurringDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((RecurringDepositProduct) product) .depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); final DepositProductRecurringDetail prodRecurringDetail = ((RecurringDepositProduct) product).depositRecurringDetail(); final DepositAccountRecurringDetail accountRecurringDetail = this.assembleAccountRecurringDetail(command, prodRecurringDetail.recurringDetail()); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountRecurringDetail, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(rdAccount); accountRecurringDetail.updateAccountReference(rdAccount); rdAccount.validateDomainRules(); account = rdAccount; } if (account != null) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(), depositAccountType.resourceName()); } return account; } public SavingsAccount assembleFrom(final Long savingsId, DepositAccountType depositAccountType) { final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId, depositAccountType); account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure .depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, productPreClosure); final DepositTermDetail updatedProductTerm = this.depositProductAssembler.assembleDepositTermDetail(command, productTerm); final BigDecimal depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName); final Integer depositPeriod = command.integerValueOfParameterNamed(depositPeriodParamName); final Integer depositPeriodFrequencyId = command.integerValueOfParameterNamed(depositPeriodFrequencyIdParamName); final SavingsPeriodFrequencyType depositPeriodFrequency = SavingsPeriodFrequencyType.fromInt(depositPeriodFrequencyId); final SavingsAccount account = null; final LocalDate expectedFirstDepositOnDate = command.localDateValueOfParameterNamed(expectedFirstDepositOnDateParamName); final Boolean trasferInterest = command.booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName); // calculate maturity amount final BigDecimal maturityAmount = null;// calculated and updated in // account final LocalDate maturityDate = null;// calculated and updated in account final DepositAccountOnClosureType accountOnClosureType = null; return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest); } public DepositAccountRecurringDetail assembleAccountRecurringDetail(final JsonCommand command, final DepositRecurringDetail prodRecurringDetail) { final BigDecimal recurringDepositAmount = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); boolean isMandatoryDeposit; boolean allowWithdrawal; boolean adjustAdvanceTowardsFuturePayments; boolean isCalendarInherited; if (command.parameterExists(isMandatoryDepositParamName)) { isMandatoryDeposit = command.booleanObjectValueOfParameterNamed(isMandatoryDepositParamName); } else { isMandatoryDeposit = prodRecurringDetail.isMandatoryDeposit(); } if (command.parameterExists(allowWithdrawalParamName)) { allowWithdrawal = command.booleanObjectValueOfParameterNamed(allowWithdrawalParamName); } else { allowWithdrawal = prodRecurringDetail.allowWithdrawal(); } if (command.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName)) { adjustAdvanceTowardsFuturePayments = command.booleanObjectValueOfParameterNamed(adjustAdvanceTowardsFuturePaymentsParamName); } else { adjustAdvanceTowardsFuturePayments = prodRecurringDetail.adjustAdvanceTowardsFuturePayments(); } if (command.parameterExists(isCalendarInheritedParamName)) { isCalendarInherited = command.booleanObjectValueOfParameterNamed(isCalendarInheritedParamName); } else { isCalendarInherited = false; } final DepositRecurringDetail depositRecurringDetail = DepositRecurringDetail.createFrom(isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments); final DepositAccountRecurringDetail depositAccountRecurringDetail = DepositAccountRecurringDetail.createNew(recurringDepositAmount, depositRecurringDetail, null, isCalendarInherited); return depositAccountRecurringDetail; } public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = this.fromApiJsonHelper.parse(json); final Collection savingsAccountTransactions = new ArrayList<>(); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale); if (element.isJsonObject()) { if (topLevelJsonElement.has(bulkSavingsDueTransactionsParamName) && topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); } final SavingsAccountTransactionDTO savingsAccountTransactionDTO = new SavingsAccountTransactionDTO(formatter, transactionDate, dueAmount, detail, new Date(), savingsId, user, depositAccountType); savingsAccountTransactions.add(savingsAccountTransactionDTO); } } } return savingsAccountTransactions; } private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { user = this.context.getAuthenticatedUserIfPresent(); } return user; } }
blob data class, long method t t f data class, long method blob 0 2661 https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java/#L107-L472 1 248 2661
2263 {"answer": "YES I found bad smells", "the bad smells are: 1. Long Method, 2. Blob, 3. Data Class, 4. Feature Envy, 5. Long Method, 6. Long Method, 7. Long Method, 8. Long Method, 9. Long Method, 10. Long Method, 11. Long Method, 12. Long Method, 13. Long Method, 14. Long Method, 15. Long Method, 16. Long Method, 17. Long Method, 18. Long Method, 19. Long Method, 20. Long Method, 21. Long Method, 22. Long Method, 23. Long Method, 24. Long Method, 25. Long Method, 26. Long Method, 27. Long Method, 28. Long Method, 29. Long Method, 30. Long Method, 31. Long Method, 32. Long Method, 33. Long Method, 34. Long Method, 35. Long Method, 36. Long Method, 37. Long Method, 38. Long Method, 39. Long Method, 40. Long Method, 41. Long Method, 42. Long Method, 43. Long Method, 44. Long Method, 45. Long Method, 46. Long Method, 47. Long Method, 48. Long Method, 49. Long Method, 50. Long Method, 51. Long Method, 52. Long Method, 53. Long Method, 54. Long Method, 55. Long Method, 56. Long Method, 57. Long Method, 58. Long Method, 59. Long Method, 60. Long Method, 61. Long Method, 62. Long Method, 63. Long Method, 64. Long Method, 65. Long Method, 66. Long Method, 67. Long Method, 68. Long Method, 69. Long Method, 70. Long Method, 71. Long Method, 72. Long Method, 73. Long Method, 74. Long Method, 75. Long Method, 76. Long Method, 77. Long Method, 78. Long Method, 79. Long Method, 80. Long Method, 81. Long Method, 82. Long Method, 83. Long Method, 84. Long Method, 85. Long Method, 86. Long Method, 87. Long Method, 88. Long Method, 89. Long Method, 90. Long Method, 91. Long Method, 92. Long Method, 93. Long Method, 94. Long Method, 95. Long Method, 96. Long Method, 97. Long Method, 98. Long Method, 99. Long Method, 100. Long Method, 101. Long Method, 102. Long Method, 103. Long Method, 104. Long Method, 105. Long Method, 106. Long Method, 107. Long Method, 108. Long Method, 109. Long Method, 110. Long Method, 111. Long Method, 112. Long Method, 113. Long Method, 114. Long Method, 115. Long Method, 116. Long Method, 117. Long Method, 118. Long Method, 119. Long Method, 120. Long Method, 121. Long Method, 122. Long Method, 123. Long Method, 124. Long Method, 125. Long Method, 126. Long Method, 127. Long Method, 128. Long Method, 129. Long Method, 130. Long Method, 131. Long Method, 132. Long Method, 133. Long Method, 134. Long Method, 135. Long Method, 136. Long Method, 137. Long Method, 138. Long Method, 139. Long Method, 140. Long Method, 141. Long Method, 142. Long Method, 143. Long Method, 144. Long Method, 145. Long Method, 146. Long Method, 147. Long Method, 148. Long Method, 149. Long Method, 150. Long Method, 151. Long Method, 152. Long Method, 153. Long Method, 154. Long Method, 155. Long Method, 156. Long Method, 157. Long Method, 158. Long Method, 159. Long Method, 160. Long Method, 161. Long Method, 162. Long Method, 163. Long Method, 164. Long Method, 165. Long Method, 166. Long Method, 167. Long Method, 168. Long Method, 169. Long Method, 170. Long Method, 171. Long Method, 172. Long Method, 173. Long Method, 174. Long Method, 175. Long Method, 176. Long Method, 177. Long Method, 178. Long Method, 179. Long Method, 180. Long Method, 181. Long Method, 182. Long Method, 183. Long Method, 184. Long Method, 185. Long Method, 186. Long Method, 187. Long Method, 188. Long Method, 189. Long Method, 190. Long Method, 191. Long Method, 192. Long Method, 193. Long Method, 194. Long Method, 195. Long Method, 196. Long Method, 197. Long Method, 198. Long Method, 199. Long Method, 200. Long Method, 201. Long Method, 202. Long Method, 203. Long Method, 204. Long Method, 205. Long Method, 206. Long Method, 207. Long Method, 208. Long Method, 209. Long Method, 210. Long Method, 211. Long Method, 212. Long Method, 213. Long Method, 214. Long Method, 215. Long Method, 216. Long Method, 217. Long Method, 218. Long Method, 219. Long Method, 220. Long Method, 221. Long Method, 222. Long Method, 223. Long Method, 224. Long Method, 225. Long Method, 226. Long Method, 227. Long Method, 228. Long Method, 229. Long Method, 230. Long Method, 231. Long Method, 232. Long Method, 233. Long Method, 234. Long Method, 235. Long Method, 236. Long Method, 237. Long Method, 238. Long Method, 239. Long Method, 240. Long Method, 241. Long Method, 242. Long Method, 243. Long Method, 244. Long Method, 245. Long Method, 246. Long Method, 247. Long Method, 248. Long Method, 249. Long Method, 250. Long Method, 251. Long Method, 252. Long Method, 253. Long Method, 254. Long Method, 255. Long Method, 256. Long Method, 257. Long Method, 258. Long Method, 259. Long Method, 260. Long Method, 261. Long Method, 262. Long Method, 263. Long Method, 264. Long Method, 265. Long Method, 266. Long Method, 267. Long Method, 268. Long Method, 269. Long Method, 270. Long Method, 271. Long Method, 272. Long Method, 273. Long Method, 274. Long Method, 275. Long Method, 276. Long Method, 277. Long Method, 278. Long Method, 279. Long Method, 280. Long Method, 281. Long Method, 282. Long Method, 283. Long Method, 284. Long Method, 285. Long Method, 286. Long Method, 287. Long Method, 288. Long Method, 289. Long Method, 290. Long Method, 291. Long Method, 292. Long Method, 293. Long Method, 294. Long Method, 295. Long Method, 296. Long Method, 297. Long Method, 298. Long Method, 299. Long Method, 300. Long Method, 301. Long Method, 302. Long Method, 303. Long Method, 304. Long Method, 305. Long Method, 306. Long Method, 307. Long Method, 308. Long Method, 309. Long Method, 310. Long Method, 311. Long Method, 312. Long Method, 313. Long Method, 314. Long Method, 315. Long Method, 316. Long Method, 317. Long Method, 318. Long Method, 319. Long Method, 320. Long Method, 321. Long Method, 322. Long Method, 323. Long Method, 324. Long Method, 325. Long Method, 326. Long Method, 327. Long Method, 328. Long Method, 329. Long Method, 330. Long Method, 331. Long Method, 332. Long Method, 333. Long Method, 334. Long Method, 335. Long Method, 336. Long Method, 337. Long Method, 338. Long Method, 339. Long Method, 340. Long Method, 341. Long Method, 342. Long Method, 343. Long Method, 344. Long Method, 345. Long Method, 346. Long Method, 347. Long Method, 348. Long Method, 349. Long Method, 350. Long Method, 351. Long Method, 352. Long Method, 353. Long Method, 354. Long Method, 355. Long Method, 356. Long Method, 357. Long Method, 358. Long Method, 359. Long Method, 360. Long Method, 361. Long Method, 362. Long Method, 363. Long Method, 364. Long Method, 365. Long Method, 366. Long Method, 367. Long Method, 368. Long Method, 369. Long Method, 370. Long Method, 371. Long Method, 372. Long Method, 373. Long Method, 374. Long Method, 375. Long Method, 376. Long Method, 377. Long Method, 378. Long Method, 379. Long Method, 380. Long Method, 381. Long Method, 382. Long Method, 383. Long Method, 384. Long Method, 385. Long Method, 386. Long Method, 387. Long Method, 388. Long Method, 389. Long Method, 390. Long Method, 391. Long Method, 392. Long Method, 393. Long Method, 394. Long Method, 395. Long Method, 396. Long Method, 397. Long Method, 398. Long Method, 399. Long Method, 400. Long Method, 401. Long Method, 402. Long Method, 403. Long Method, 404. Long Method, 405. Long Method, 406. Long Method, 407. Long Method, 408. Long Method, 409. Long Method, 410. Long Method, 411. Long Method, 412. Long Method, 413. Long Method, 414. Long Method, 415. Long Method, 416. Long Method, 417. Long Method, 418. Long Method, 419. Long Method, 420. Long Method, 421. Long Method, 422. Long Method, 423. Long Method, 424. Long Method, 425. Long Method, 426. Long Method, 427. Long Method, 428. Long Method, 429. Long Method, 430. Long Method, 431. Long Method, 432. Long Method, 433. Long Method, 434. Long Method, 435. Long Method, 436. Long Method, 437. Long Method, 438. Long Method, 439. Long Method, 440. Long Method, 441. Long Method, 442. Long Method, 443. Long Method, 444. Long Method, 445. Long Method, 446. Long Method, 447. Long Method, 448. Long Method, 449. Long Method, 450. Long Method, 451. Long Method, 452. Long Method, 453. Long Method, 454. Long Method, 455. Long Method, 456. Long Method, 457. Long Method, 458. Long Method, 459. Long Method, 460. Long Method, 461. Long Method, 462. Long Method, 463. Long Method, 464. Long Method, 465. Long Method, 466. Long Method, 467. Long Method, 468. Long Method, 469. Long Method, 470. Long Method, 471. Long Method, 472. Long Method, 473. Long Method, 474. Long Method, 475. Long Method, 476. Long Method, 477. Long Method, 478. Long Method, 479. Long Method, 480. Long Method, 481. Long Method, 482. Long Method, 483. Long Method, 484. Long Method, 485. Long Method, 486. Long Method, 487. Long Method, 488. Long Method, 489. Long Method, 490. Long Method, 491. Long Method, 492. Long Method, 493. Long Method, 494. Long Method, 495. Long Method, 496. Long Method, 497. Long Method, 498. Long Method, 499. Long Method, 500. Long Method, 501. Long Method, 502. Long Method, 503. Long Method, 504. Long Method, 505. Long Method, 506. Long Method, 507. Long Method, 508. Long Method, 509. Long Method, 510. Long Method, 511. Long Method, 512. Long Method, 513. Long Method, 514. Long Method, 515. Long Method, 516. Long Method, 517. Long Method, 518. Long Method, 519. Long Method, 520. Long Method, 521. Long Method, 522. Long Method, 523. Long Method, 524. Long Method, 525. Long Method, 526. Long Method, 527. Long Method, 528. Long Method, 529. Long Method, 530. Long Method, 531. Long Method, 532. Long Method, 533. Long Method, 534. Long Method, 535. Long Method, 536. Long Method, 537. Long Method, 538. Long Method, 539. Long Method, 540. Long Method, 541. Long Method, 542. Long Method, 543. Long Method, 544. Long Method, 545. Long Method, 546. Long Method, 547. Long Method, 548. Long Method, 549. Long Method, 550. Long Method, 551. Long Method, 552. Long Method, 553. Long Method, 554. Long Method, 555. Long Method, 556. Long Method, 557. Long Method, 558. Long Method, 559. Long Method, 560. Long Method, 561. Long Method, 562. Long Method, 563. Long Method, 564. Long Method, 565. Long Method, 566. Long Method, 567. Long Method, 568. Long Method, 569. Long Method, 570. Long Method, 571. Long Method, 572. Long Method, 573. Long Method, 574. Long Method, 575. Long Method, 576. Long Method, 577. Long Method, 578. Long Method, 579. Long Method, 580. Long Method, 581. Long Method, 582. Long Method, 583. Long Method, 584. Long Method, 585. Long Method, 586. Long Method, 587. Long Method, 588. Long Method, 589. Long Method, 590. Long Method, 591. Long Method, 592. Long Method, 593. Long Method, 594. Long Method, 595. Long Method, 596. Long Method, 597. Long Method, 598. Long Method, 599. Long Method, 600. Long Method, 601. Long Method, 602. Long Method, 603. Long Method, 604. Long Method, 605. Long Method, 606. Long Method, 607. Long Method, 608. Long Method, 609. Long Method, 610. Long Method, 611. Long Method, 612. Long Method, 613. Long Method, 614. Long Method, 615. Long Method, 616. Long Method, 617. Long Method, 618. Long Method, 619. Long Method, 620. Long Method, 621. Long Method, 622. Long Method, 623. Long Method, 624. Long Method, 625. Long Method, 626. Long Method, 627. Long Method, 628. Long Method, 629. Long Method, 630. Long Method, 631. Long Method, 632. Long Method, 633. Long Method, 634. Data Class, 635. Long Method, 636. Long Method, 637. Data Class, 638. Blob, 639. Data Class, 640. Blob, 641. Data Class, 642. Blob, 643. Data Class, 644. Blob, 645. Data Class, 646. Blob, 647. Data Class, 648. Blob, 649. Data Class, 650. Blob, 651. Data Class, 652. Blob, 653. Data Class, 654. Blob, 655. Data Class, 656. Blob, 657. Data Class, 658. Blob, 659. Data Class, 660. Blob, 661. Data Class, 662. Blob, 663. Data Class, 664. Blob, 665. Data Class, 666. Blob, 667. Data Class, 668. Blob, 669. Data Class, 670. Blob, 671. Data Class, 672. Blob, 673. Data Class, 674. Blob, 675. Data Class, 676. Blob, 677. Data Class, 678. Blob, 679. Data Class, 680. Blob, 681. Data Class, 682. Blob, 683. Data Class, 684. Blob, The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } }
blob  Long Method, 2 Blob, 3 Data Class, 4 Feature Envy, 5 Long Method, 6 Long Method, 7 Long Method, 8 Long Method, 9 Long Method, t f t . Long Method, 3. Data Class, 4. Feature Envy, 5. Long Method, 6. Long Method, 7. Long Method, 8. Long Method, 9. Long Method,   0 13723 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 1 2263 13723
1908 {"response": "YES I found bad smells the bad smells are: 1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } }
blob 1. data class t t f 1. data class blob 0 12396 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 1 1908 12396
2560      { "message": "YES, I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } }
blob data class, long method t t f data class, long method blob 0 14836 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 1 2560 14836
2415 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } }
blob data class t t f data class blob 0 14419 https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 1 2415 14419
1788  { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } }
blob 1 Long Method, 2 Data Class t f f 1. Long Method, 2. Data Class blob 0 11983 https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 1 1788 11983
884 { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); }
long method 1. long method, 2. data class t t t  2. data class   0 8035 https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 1 884 8035
242 { "output": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } }
blob data class, long method t t f data class, long method blob 0 2644 https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 1 242 2644
1018     { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); }
feature envy long method, data class t t f long method, data class feature envy 0 9334 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 1 1018 9334
2705    { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } }
blob data class, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method t t f data class, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method, long method blob 0 15343 https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 1 2705 15343
1000  {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); }
long method data class t t f data class long method 0 9174 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 1 1000 9174
552  {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class WireAdminImpl implements WireAdmin, ServiceListener { private BundleContext m_bundleContext; // A Map containing a service reference associated to a producer and a List // of wire objects private Map m_consumers = new HashMap(); /* ServiceReferences, List */ private Map m_producers = new HashMap(); /* ServiceReferences, List */ private List m_wires; // List containing the wires //private BindingController wireAdminListenersBindingController; // Filter corresponding to a consumer service private Filter m_consumerFilter; // Filter corresponding to a producer service private Filter m_producerFilter; // EventManager private EventManager m_eventManager; private static int m_wireCount = 0; private AsyncMethodCaller m_asyncMethodCaller = new AsyncMethodCaller(); //m_eventDispatcher.stop(); private static PrintStream m_traceout = null; private static PrintStream m_errorout = System.err; /** * Constructor with package visibility * * @param bundleContext the bundle context */ WireAdminImpl(BundleContext bundleContext) { m_bundleContext = bundleContext; if(bundleContext.getProperty("fr.imag.adele.wireadmin.trace") != null) { String value = bundleContext.getProperty("fr.imag.adele.wireadmin.trace"); if(value.equals("true")) { m_traceout = System.out; } } // Create the event manager (the event manager will start its own thread) m_eventManager = new EventManager(m_bundleContext); try { m_producerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Producer)"); m_consumerFilter = m_bundleContext.createFilter( "(objectClass=org.osgi.service.wireadmin.Consumer)"); } catch (InvalidSyntaxException e) { // never thrown since LDAP expressions are correct } // Recover persistent wires getPersistentWires(); // Activate thread that does asynchronous calls to // the producersConnected and consummersConnected methods new Thread(m_asyncMethodCaller).start(); // Gets all producers and consumers that are present at the // moment the wire admin is created try { // Registration for events must be done first, as some service // can be registered during initialization m_bundleContext.addServiceListener(this,"(|"+m_producerFilter.toString()+m_consumerFilter.toString()+")"); // Replacement for the two following lines which work under OSCAR, // but not work under IBM's SMF //m_bundleContext.addServiceListener(this,m_consumerFilter.toString()); //m_bundleContext.addServiceListener(this,m_producerFilter.toString()); // Get all producers ServiceReference[] producerRefs = m_bundleContext.getServiceReferences(Producer.class.getName(),null); if(producerRefs!=null) { // lock the producers Map to avoid concurrent modifications due // to service events synchronized(m_producers) { for(int i=0;iWire object that connects a Producer * service to a Consumer service. * * The Producer service and Consumer service do not * have to be registered when the Wire object is created. * * The Wire configuration data must be persistently stored. * All Wire connections are reestablished when the * WireAdmin service is registered. * A Wire can be permanently removed by using the * {@link #deleteWire} method. * * The Wire object's properties must have case * insensitive String objects as keys (like the Framework). * However, the case of the key must be preserved. * The type of the value of the property must be one of the following: * * * type = basetype * | vector | arrays * * basetype = String | Integer | Long * | Float | Double | Byte * | Short | Character * | Boolean * * primitive = long | int | short * | char | byte | double | float * * arrays = primitive '[]' | basetype '[]' * * vector = Vector of basetype * * * The WireAdmin service must automatically add the * following Wire properties: * * * {@link WireConstants#WIREADMIN_PID} set to the value of the Wire object's * persistent identity (PID). This value is generated by the * Wire Admin service when a Wire object is created. * * * {@link WireConstants#WIREADMIN_PRODUCER_PID} set to the value of * Producer service's PID. * * * {@link WireConstants#WIREADMIN_CONSUMER_PID} set to the value of * Consumer service's PID. * * * If the properties argument * already contains any of these keys, then the supplied values * are replaced with the values assigned by the Wire Admin service. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_CREATED} * after the new Wire object becomes available from {@link #getWires}. * * @param producerPID The service.pid of the Producer service * to be connected to the Wire object. * @param consumerPID The service.pid of the Consumer service * to be connected to the Wire object. * @param properties The Wire object's properties. This argument may be null * if the caller does not wish to define any Wire object's properties. * @return The Wire object for this connection. * @throws java.lang.IllegalArgumentException If * properties contains case variants of the same key name. */ public Wire createWire(String producerPID, String consumerPID, Dictionary props) { ServiceReference producerServiceRef = null; ServiceReference consumerServiceRef = null; Dictionary properties; if(props == null) { properties = new Hashtable(); } else { //Clone the dictionary properties = cloneProperties(props); } // Addition of mandatory properties properties.put(WireConstants.WIREADMIN_CONSUMER_PID, consumerPID); properties.put(WireConstants.WIREADMIN_PRODUCER_PID, producerPID); properties.put(WireConstants.WIREADMIN_PID, generateWirePID()); // p.327 "Wire objects can be created when the producer or consumer // service is not registered WireImpl wire = new WireImpl(producerPID, consumerPID, properties); // Initialize the wire wire.initialize(m_bundleContext,m_eventManager); // Add the wire to the list synchronized(m_wires) { m_wires.add(wire); } // p. 357 "The Wire Admin service must broadcast a WireAdminEvent of // type WireAdminEvent.WIRE_CREATED after the new Wire object becomes // available from getWires(java.lang.String)." m_eventManager.fireEvent(WireAdminEvent.WIRE_CREATED,wire); synchronized (m_producers) { Iterator producerIterator = m_producers.keySet().iterator(); while(producerIterator.hasNext()) { producerServiceRef = (ServiceReference) producerIterator.next(); if (producerServiceRef.getProperty(Constants.SERVICE_PID).equals(producerPID)) { wire.bindProducer(producerServiceRef); break; } } } synchronized (m_consumers) { Iterator consumerIterator = m_consumers.keySet().iterator(); while(consumerIterator.hasNext()) { consumerServiceRef = (ServiceReference) consumerIterator.next(); if (consumerServiceRef.getProperty(Constants.SERVICE_PID).equals(consumerPID)) { wire.bindConsumer(consumerServiceRef); break; } } } // p.327 If both Producer and Consumer services are registered, they are // connected by the wire admin service. if(wire.isConnected()) { List wires = (List) m_producers.get(producerServiceRef); wires.add(wire); m_asyncMethodCaller.consumersConnected(wire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(consumerServiceRef); wires.add(wire); m_asyncMethodCaller.producersConnected(wire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // Newly created wires are immediately persisted to avoid information // loss in case of crashes. (spec not clear about this) persistWires(); return wire; } /** * Delete a Wire object. * * The Wire object representing a connection between * a Producer service and a Consumer service must be * removed. * The persistently stored configuration data for the Wire object * must destroyed. The Wire object's method {@link Wire#isValid} will return false * after it is deleted. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_DELETED} * after the Wire object becomes invalid. * * @param wire The Wire object which is to be deleted. */ public void deleteWire(Wire wire) { if(m_wires.contains(wire)) { WireImpl wireImpl = (WireImpl) wire; m_wires.remove(wire); if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); wires.remove(wireImpl); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } wireImpl.invalidate(); // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_DELETED,wireImpl); // Persist state to avoid losses in case of crashes (spec not clear about this). persistWires(); } else { traceln("WireAdminImpl: Cannot delete a wire that is not managed by this service"); } } /** * Update the properties of a Wire object. * * The persistently stored configuration data for the Wire object * is updated with the new properties and then the Consumer and Producer * services will be called at the respective {@link Consumer#producersConnected} * and {@link Producer#consumersConnected} methods. * * The Wire Admin service must broadcast a WireAdminEvent of type * {@link WireAdminEvent#WIRE_UPDATED} * after the updated properties are available from the Wire object. * * @param wire The Wire object which is to be updated. * @param properties The new Wire object's properties or null if no properties are required. */ public void updateWire(Wire wire, Dictionary props) { if(m_wires.contains(wire) == false) { traceln("WireAdminImpl: Cannot update a wire that is not managed by this service"); return; } // Clone the dictionary Dictionary properties = cloneProperties(props); // Put again the mandatory properties, in case they are not set properties.put(WireConstants.WIREADMIN_CONSUMER_PID,wire.getProperties().get(WireConstants.WIREADMIN_CONSUMER_PID)); properties.put(WireConstants.WIREADMIN_PRODUCER_PID,wire.getProperties().get(WireConstants.WIREADMIN_PRODUCER_PID)); properties.put(WireConstants.WIREADMIN_PID,wire.getProperties().get(WireConstants.WIREADMIN_PID)); WireImpl wireImpl = (WireImpl) wire; wireImpl.updateProperties(properties); // Call methods on Consumer and Producer if(wireImpl.isConnected()) { List wires = (List) m_producers.get(wireImpl.getProducerServiceRef()); m_asyncMethodCaller.consumersConnected(wireImpl.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); wires = (List) m_consumers.get(wireImpl.getConsumerServiceRef()); m_asyncMethodCaller.producersConnected(wireImpl.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); } // fire an event m_eventManager.fireEvent(WireAdminEvent.WIRE_UPDATED,wireImpl); } /** * Return the Wire objects that match the given filter. * * The list of available Wire objects is matched against the * specified filter. Wire objects which match the * filter must be returned. These Wire objects are not necessarily * connected. The Wire Admin service should not return * invalid Wire objects, but it is possible that a Wire * object is deleted after it was placed in the list. * * The filter matches against the Wire object's properties including * {@link WireConstants#WIREADMIN_PRODUCER_PID}, {@link WireConstants#WIREADMIN_CONSUMER_PID} * and {@link WireConstants#WIREADMIN_PID}. * * @param filter Filter string to select Wire objects * or null to select all Wire objects. * @return An array of Wire objects which match the filter * or null if no Wire objects match the filter. * @throws org.osgi.framework.InvalidSyntaxException If the specified filter * has an invalid syntax. * @see org.osgi.framework.Filter */ public Wire[] getWires(String filter) throws InvalidSyntaxException { List res = null; if (filter == null) { return (Wire [])m_wires.toArray(new Wire[m_wires.size()]); } else { Filter tempFilter = m_bundleContext.createFilter(filter); Iterator iter = m_wires.iterator(); while (iter.hasNext()) { WireImpl currentWire = (WireImpl) iter.next(); if (tempFilter.match(currentWire.getProperties())) { if (res == null) { res = new ArrayList(); } res.add(currentWire); } } } if (res == null) { return null; } else { return (Wire [])res.toArray(new Wire[res.size()]); } } /** * listens Producer and Consumer services changes * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent) */ public void serviceChanged(ServiceEvent e) { ServiceReference serviceRef = e.getServiceReference(); // A consumer service changed if (m_consumerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("consumer registered"); List wires = new ArrayList(); synchronized(m_consumers) { m_consumers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived consumer currentWire.bindConsumer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])wires.toArray(new Wire[wires.size()])); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.add(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } } } if(!called) { // P. 329 "If the Consumer service has no Wire objects attached when it // is registered, the WireAdmin service must always call producersConnected(null) m_asyncMethodCaller.producersConnected((Consumer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("consumer unregistering"); synchronized(m_consumers) { m_consumers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getConsumerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindConsumer(); List producerWires = (List) m_producers.get(currentWire.getProducerServiceRef()); producerWires.remove(currentWire); m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])producerWires.toArray(new Wire[producerWires.size()])); } else { currentWire.unbindConsumer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to consumer service modification traceln("consumer service modified"); break; } } // Removed else to manage services which are both producers AND consumers if (m_producerFilter.match(serviceRef)) { switch (e.getType()) { case ServiceEvent.REGISTERED : traceln("producer registered"); List wires = new ArrayList(); synchronized(m_producers) { m_producers.put(serviceRef,wires); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); boolean called = false; // Iterate over all existing wires while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // This wire is associated to the newly arrived producer currentWire.bindProducer(serviceRef); if(currentWire.isConnected()) { // The wire has been connected, both producer and consumer // must be updated wires.add(currentWire); called = true; m_asyncMethodCaller.consumersConnected(currentWire.getProducer(),(Wire[])wires.toArray(new Wire[wires.size()])); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.add(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } } } if(!called) { // P. 329 "If the Producer service has no Wire objects attached when it // is registered, the WireAdmin service must always call consumersConnected(null) m_asyncMethodCaller.consumersConnected((Producer) m_bundleContext.getService(serviceRef),null); } } break; case ServiceEvent.UNREGISTERING : traceln("Producer unregistering"); synchronized(m_producers) { m_producers.remove(serviceRef); } synchronized(m_wires) { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); if(currentWire.getProducerPID().equals(serviceRef.getProperty(Constants.SERVICE_PID))) { // p. 328 "When a Consumer or Producer service is unregistered // from the OSGi framework, the other object in the association // is informed that the Wire object is no longer valid" if(currentWire.isConnected()) { currentWire.unbindProducer(); List consumerWires = (List) m_consumers.get(currentWire.getConsumerServiceRef()); consumerWires.remove(currentWire); m_asyncMethodCaller.producersConnected(currentWire.getConsumer(),(Wire[])consumerWires.toArray(new Wire[consumerWires.size()])); } else { currentWire.unbindProducer(); } } } } break; case ServiceEvent.MODIFIED : // TODO Respond to producer service modification traceln("producer service modified"); break; } } } /** * release all references before stop */ synchronized void releaseAll() { Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.invalidate(); } Iterator producerIt = m_producers.keySet().iterator(); while (producerIt.hasNext()) { ServiceReference producerRef = (ServiceReference) producerIt.next(); ((Producer)m_bundleContext.getService(producerRef)).consumersConnected(null); } Iterator consumerIt = m_consumers.keySet().iterator(); while (consumerIt.hasNext()) { ServiceReference consumerRef = (ServiceReference) consumerIt.next(); ((Consumer)m_bundleContext.getService(consumerRef)).producersConnected(null); } // Stop the thread m_asyncMethodCaller.stop(); // Notify the event manager so that it stops its thread m_eventManager.stop(); persistWires(); } /** * This method generates a PID. The pid is generated from the bundle id, * a hash code from the current time and a counter. * * @return a wire PID */ private String generateWirePID() { Date d = new Date(); String PID="wire."+m_bundleContext.getBundle().getBundleId()+d.hashCode()+m_wireCount; m_wireCount ++; // Maybe the counter should go above 9? if(m_wireCount>9) { m_wireCount = 0; } return PID; } /** * Recover persistent wires * */ private void getPersistentWires() { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(m_bundleContext.getDataFile("wires.ser"))); m_wires = (ArrayList) ois.readObject(); ois.close(); if(m_wires!=null) { traceln("Deserialized "+m_wires.size()+" wires"); Iterator wireIt = m_wires.iterator(); while(wireIt.hasNext()) { WireImpl currentWire = (WireImpl) wireIt.next(); currentWire.initialize(m_bundleContext,m_eventManager); } } else { traceln("Couldn't Deserialize wires"); m_wires = new ArrayList(); } } catch(FileNotFoundException ex) { // do not show anything as this exception is thrown every // time the wire admin service is launched for the first // time m_wires = new ArrayList(); } catch(Exception ex) { trace(ex); m_wires = new ArrayList(); } } /** * Persist existing wires * */ private void persistWires() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(m_bundleContext.getDataFile("wires.ser"))); oos.writeObject(m_wires); oos.close(); traceln("Serialized "+m_wires.size()+" wires"); } catch(Exception ex) { trace(ex); } } /** * print an error * @param message message to error */ static void error(String message) { if (m_errorout != null) { m_errorout.println(message); } } /** * print a trace * @param message message to trace */ static void traceln(String message) { if (m_traceout != null) { trace(message); trace("\n"); } } /** * print a trace * @param message message to trace */ static void trace(String message) { if (m_traceout != null) { m_traceout.print(message); } } /** * print a trace * @param e exception to trace */ static void trace(Exception e) { if (m_traceout != null) { e.printStackTrace(m_traceout); } } /** * Clone a dictionary * * @param dictionary The dictionary to clone * @return a copy of the dicionary */ private Dictionary cloneProperties(Dictionary dictionary){ Dictionary properties=new Hashtable(); if (dictionary == null) { properties = new Hashtable(); } else { Enumeration enumeration=dictionary.keys(); while(enumeration.hasMoreElements()){ Object key=enumeration.nextElement(); Object value=dictionary.get(key); properties.put(key,value); } } return properties; } /** * This class enables calls to Producer.consumersConnected and Consumer.producersConnected * to be done asynchronously * * p.333 "The WireAdmin service can call the consumersConnected or producersConnected * methods during the registration of the consumer of producer service" * **/ class AsyncMethodCaller implements Runnable { private boolean m_stop = false; private List m_methodCallStack = new ArrayList(); public void run() { while (!m_stop) { Object nextTarget[] = null; synchronized (m_methodCallStack) { while (m_methodCallStack.size() == 0) { try { m_methodCallStack.wait(); } catch (InterruptedException ex) { // Ignore. } } nextTarget = (Object[]) m_methodCallStack.remove(0); } if(nextTarget[0] instanceof Producer) { try { ((Producer)nextTarget[0]).consumersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } // Removed else because nextTarget can be both producer and consumer if(nextTarget[0] instanceof Consumer) { try { ((Consumer)nextTarget[0]).producersConnected((Wire[])nextTarget[1]); } catch(Exception ex) { trace(ex); } } } } /** * Place a call to Consumer.producersConnected on the stack * * @param c the consumer * @param wires the wires */ public void producersConnected(Consumer c,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{c,wires}); m_methodCallStack.notify(); } } /** * Place a call to Producer.consumersConnected on the stack * * @param p the producer * @param wires the wires */ public void consumersConnected(Producer p,Wire []wires) { synchronized (m_methodCallStack) { m_methodCallStack.add(new Object[]{p,wires}); m_methodCallStack.notify(); } } /** * stop the dispatcher * */ void stop() { m_stop = true; } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 5572 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/wireadmin/src/main/java/org/apache/felix/wireadmin/WireAdminImpl.java/#L71-L1037 1 552 5572
159    { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class AssignmentTask implements Runnable { final Map> assignmentFailures; HostAndPort location; private Map> assignmentsPerTablet; public AssignmentTask(Map> assignmentFailures, String location, Map> assignmentsPerTablet) { this.assignmentFailures = assignmentFailures; this.location = HostAndPort.fromString(location); this.assignmentsPerTablet = assignmentsPerTablet; } private void handleFailures(Collection failures, String message) { for (KeyExtent ke : failures) { List mapFiles = assignmentsPerTablet.get(ke); synchronized (assignmentFailures) { for (PathSize pathSize : mapFiles) { List existingFailures = assignmentFailures.get(pathSize.path); if (existingFailures == null) { existingFailures = new ArrayList<>(); assignmentFailures.put(pathSize.path, existingFailures); } existingFailures.add(ke); } } log.info("Could not assign {} map files to tablet {} because : {}. Will retry ...", mapFiles.size(), ke, message); } } @Override public void run() { HashSet uniqMapFiles = new HashSet<>(); for (List mapFiles : assignmentsPerTablet.values()) for (PathSize ps : mapFiles) uniqMapFiles.add(ps.path); log.debug("Assigning {} map files to {} tablets at {}", uniqMapFiles.size(), assignmentsPerTablet.size(), location); try { List failures = assignMapFiles(context, location, assignmentsPerTablet); handleFailures(failures, "Not Serving Tablet"); } catch (AccumuloException | AccumuloSecurityException e) { handleFailures(assignmentsPerTablet.keySet(), e.getMessage()); } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 1984 https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/client/BulkImporter.java/#L449-L499 1 159 1984
95 { "output": "YES I found bad smells\nthe bad smells are: Blob, Long Method, Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } }
blob blob, long method, data class t t t  long method, data class   0 1268 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 1 95 1268
581  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } }
long method long method, data class t t t  data class   0 5786 https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 1 581 5786
2901  {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); }
long method long method, data class t t t  data class   0 2195 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 1 2901 2195
1465 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } }
blob data class, long method t t f data class, long method blob 0 11030 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 1 1465 11030
1281 YES I found bad smells YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class used as interface 4. Anemic domain model 5. Code duplication 6. Nested classes without clear hierarchy or purpose 7. Use of interface for a single implementation class 8. Overriding default method in interface 9. Misuse of the Builder pattern 10. Mismatched naming conventions 11. Poor encapsulation and information hiding I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } }
blob  Long method2 Feature envy3 Data class used as interface4 Anemic domain model5 Code duplication6 Nested classes without clear hierarchy or purpose7 Use of interface for a single implementation class8 Overriding default method in interface9 Misuse of the Builder pattern t f f . Long method2. Feature envy3. Data class used as interface4. Anemic domain model5. Code duplication6. Nested classes without clear hierarchy or purpose7. Use of interface for a single implementation class8. Overriding default method in interface9. Misuse of the Builder pattern blob 0 10595 https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 2 1281 10595
786 {"result": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } }
blob data class, long method t t f data class, long method blob 0 7505 https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 1 786 7505
1849 { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } }
blob long method, data class t t f long method, data class blob 0 12187 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 1 1849 12187
4484 {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } }
blob blob, data class, long method t t t  data class, long method   0 11873 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 1 4484 11873
2368 {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } }
long method long method, data class t t t  data class   0 14301 https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 1 2368 14301
1448 { "response": "YES I found bad smells", "detected_bad_smells": [ { "1. Data class" : "The class has only data attributes and getter/setter methods." }, { "2. Long Method" : "The methods writeAsElement and readFromElement are quite long and may need refactoring." } ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } }
blob 1. data class: the class has only data attributes and getter/setter methods., 2. long method: the methods writeaselement and readfromelement are quite long and may need refactoring. t t f 1. data class: the class has only data attributes and getter/setter methods., 2. long method: the methods writeaselement and readfromelement are quite long and may need refactoring. blob 0 10989 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 1 1448 10989
3589      { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); }
long method long method, data class t t t  data class   0 7923 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 1 3589 7923
926 { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } }
blob data class t t f data class blob 0 8312 https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 1 926 8312
2384    { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } }
blob data class t t f data class blob 0 14343 https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 1 2384 14343
2302      { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } }
long method long method, data class t t t  data class   0 14043 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 1 2302 14043
165 { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ConfigurationListener extends Phase implements org.osgi.service.cm.ConfigurationListener { public static class Builder { public Builder(ContainerState containerState) { _containerState = containerState; } public Builder component(Component component) { _component = component; return this; } public ConfigurationListener build() { Objects.requireNonNull(_component); return new ConfigurationListener(_containerState, _component); } private Component _component; private final ContainerState _containerState; } protected ConfigurationListener( ContainerState containerState, Component component) { super(containerState, component); _component = component; _log = containerState.containerLogs().getLogger(getClass()); } @Override public boolean close() { try (Syncro open = syncro.open()) { if (_listenerService != null) { _listenerService.unregister(); _listenerService = null; } return next.map( next -> { submit(next.closeOp(), next::close).onFailure( f -> { _log.error(l -> l.error("CCR Failure in configuration listener close on {}", next, f)); error(f); } ); return true; } ).orElse(true); } } @Override public Op closeOp() { return Op.of(Mode.CLOSE, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public void configurationEvent(ConfigurationEvent event) { next.map(next -> (Component)next).ifPresent( next -> next.configurationTemplates().stream().filter( t -> Predicates.isMatchingConfiguration(event).test(t) ).findFirst().ifPresent( t -> { String eventString = Arrays.asList(event.getPid(), event.getFactoryPid(), type(event)).toString(); Promise result = containerState.submit( Op.of(Mode.OPEN, Type.CONFIGURATION_EVENT, eventString), () -> { _log.debug(l -> l.debug("CCR Event {} matched {} because of {}", eventString, _component.template().name, _component.template().configurations)); processEvent(next, t, event); return true; } ); try { result.getValue(); } catch (Exception e) { Throw.exception(e); } } ) ); } @Override public boolean open() { try (Syncro open = syncro.open()) { if (containerState.bundleContext() == null) { // this bundle was already removed return false; } Dictionary properties = new Hashtable<>(); properties.put("name", toString()); properties.put(Constants.SERVICE_DESCRIPTION, "Aries CDI - Configuration Listener for " + containerState.bundle()); properties.put(Constants.SERVICE_VENDOR, "Apache Software Foundation"); _listenerService = containerState.bundleContext().registerService( org.osgi.service.cm.ConfigurationListener.class, this, properties); return next.map(next -> (Component)next).map( component -> { submit(component.openOp(), component::open).then( s -> { component.configurationTemplates().stream().filter( ct -> Objects.nonNull(ct.pid) ).forEach( template -> { if (template.maximumCardinality == MaximumCardinality.ONE) { containerState.findConfig(template.pid).ifPresent( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, null, c.getPid())) ); } else { containerState.findConfigs(template.pid, true).ifPresent( arr -> Arrays.stream(arr).forEach( c -> processEvent( component, template, new ConfigurationEvent( containerState.caTracker().getServiceReference(), ConfigurationEvent.CM_UPDATED, c.getFactoryPid(), c.getPid())) ) ); } } ); return s; }, f -> { _log.error(l -> l.error("CCR Failure during configuration start on {}", next, f.getFailure())); error(f.getFailure()); } ); return true; } ).orElse(true); } } @Override public Op openOp() { return Op.of(Mode.OPEN, Type.CONFIGURATION_LISTENER, _component.template().name); } @Override public String toString() { return Arrays.asList(getClass().getSimpleName(), _component).toString(); } private void processEvent(Component component, ConfigurationTemplateDTO t, ConfigurationEvent event) { boolean required = t.policy == ConfigurationPolicy.REQUIRED; boolean single = t.maximumCardinality == MaximumCardinality.ONE; switch (event.getType()) { case ConfigurationEvent.CM_DELETED: component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { if (!required) { instance.configurations.removeIf( c -> c.template == t ); submit(instance.openOp(), instance::open); } else { component.instances().remove(instance); } return s; } ); } ); return; case ConfigurationEvent.CM_LOCATION_CHANGED: break; case ConfigurationEvent.CM_UPDATED: if (!single && !component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> event.getPid().equals(instance.pid) ).findFirst().isPresent()) { ExtendedComponentInstanceDTO instance = new ExtendedComponentInstanceDTO( containerState, _component.activatorBuilder()); instance.activations = new CopyOnWriteArrayList<>(); instance.configurations = new CopyOnWriteArrayList<>(); instance.pid = event.getPid(); instance.references = new CopyOnWriteArrayList<>(); instance.template = component.template(); component.instances().add(instance); } containerState.findConfig(event.getPid()).ifPresent( configuration -> { ExtendedConfigurationDTO configurationDTO = new ExtendedConfigurationDTO(); configurationDTO.configuration = configuration; configurationDTO.pid = configuration.getPid(); configurationDTO.properties = Maps.of(configuration.getProcessedProperties(event.getReference())); configurationDTO.template = t; component.instances().stream().map( ExtendedComponentInstanceDTO.class::cast ).filter( instance -> (!single && event.getPid().equals(instance.pid)) || single ).forEach( instance -> { submit(instance.closeOp(), instance::close).then( s -> { instance.configurations.removeIf(c -> c.template == t); instance.configurations.add(configurationDTO); submit(instance.openOp(), instance::open); return s; } ); } ); } ); break; } } private String type(ConfigurationEvent event) { if (event.getType() == ConfigurationEvent.CM_DELETED) return "DELETED"; if (event.getType() == ConfigurationEvent.CM_LOCATION_CHANGED) return "LOCATION_CHANGED"; if (event.getType() == ConfigurationEvent.CM_UPDATED) return "UPDATED"; throw new IllegalArgumentException("CM Event type " + event.getType()); } private volatile ServiceRegistration _listenerService; private final Component _component; private final Logger _log; }
blob data class, long method t t f data class, long method blob 0 2008 https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/ConfigurationListener.java/#L42-L310 1 165 2008
2548      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; }
long method long method, data class t t t  data class   0 14793 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 1 2548 14793
366    { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; }
long method 1. long method, 2. data class t t f  2. data class long method 0 3740 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 1 366 3740
1841   {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; }
feature envy Long Method, Data Class t f f Long Method, Data Class feature envy 0 12150 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 1 1841 12150
2298      { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); }
long method long method, data class t t t  data class   0 14025 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 1 2298 14025
1867      {"message": "YES I found bad smells", "bad smells are": ["1. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } }
blob 1. data class t t f 1. data class blob 0 12239 https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 1 1867 12239
768 { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } }
blob data class t t f data class blob 0 7237 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 1 768 7237
4976 {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } }
blob data class, long method t t f data class, long method blob 0 13623 https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 1 4976 13623
1432 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); }
long method long method, data class t t t  data class   0 10956 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 1 1432 10956
426 {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean equals(Object that) { if( !(that instanceof PlanningCoCodingGroup) ) return false; PlanningCoCodingGroup thatgrp = (PlanningCoCodingGroup) that; return Arrays.equals(_colIndexes, thatgrp._colIndexes); }
feature envy data class t t f data class feature envy 0 4264 https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/compress/cocode/PlanningCoCodingGroup.java/#L116-L123 1 426 4264
132 { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } }
blob long method, data class t t f long method, data class blob 0 1631 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 1 132 1631
623 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } }
feature envy long method, data class t t f long method, data class feature envy 0 6248 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 1 623 6248
277  {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 2971 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 1 277 2971
2538 {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 14768 https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 1 2538 14768
5046 {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } }
blob data class, long method t t f data class, long method blob 0 14099 https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 1 5046 14099
3803   { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 9644 https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 1 3803 9644
2653 { "output": "YES I found bad smells. the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
} ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) {
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 15178 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 1 2653 15178
2049 {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class","Blob"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } }
blob long method, data class, blob t t t long method, data class   0 12883 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 1 2049 12883
613  { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } }
blob long method, data class t t f long method, data class blob 0 6167 https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 1 613 6167
1929 {"message": "YES I found bad smells","bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } }
blob data class t t f data class blob 0 12452 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 1 1929 12452
4034      { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } }
feature envy the bad smells are: long method, data class t t f the bad smells are: long method, data class feature envy 0 10674 https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 1 4034 10674
1901 { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } }
long method 1. long method, 2. data class t t f  2. data class long method 0 12362 https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 1 1901 12362
2394 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private static final String INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; static final int RPS = 0; static final int SETTINGS = 1; static final int CONTENT = 2; static final int FRAGMENT_COUNT = CONTENT +1; private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]; private MenuItem settings; private MenuItem challenge; private MenuItem share; private MenuItem message; private boolean isResumed = false; private boolean hasNativeLink = false; private CallbackManager callbackManager; private GameRequestDialog gameRequestDialog; private AccessTokenTracker accessTokenTracker; @Override public void onCreate(Bundle savedInstanceState) { FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS); FacebookSdk.setIsDebugEnabled(true); super.onCreate(savedInstanceState); accessTokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (isResumed) { if (currentAccessToken == null) { showFragment(RPS, false); } } } }; setContentView(R.layout.main); FragmentManager fm = getSupportFragmentManager(); fragments[RPS] = fm.findFragmentById(R.id.rps_fragment); fragments[SETTINGS] = fm.findFragmentById(R.id.settings_fragment); fragments[CONTENT] = fm.findFragmentById(R.id.content_fragment); FragmentTransaction transaction = fm.beginTransaction(); for(int i = 0; i < fragments.length; i++) { transaction.hide(fragments[i]); } transaction.commit(); hasNativeLink = handleNativeLink(); gameRequestDialog = new GameRequestDialog(this); callbackManager = CallbackManager.Factory.create(); gameRequestDialog.registerCallback( callbackManager, new FacebookCallback() { @Override public void onCancel() { Log.d(TAG, "Canceled"); } @Override public void onError(FacebookException error) { Log.d(TAG, String.format("Error: %s", error.toString())); } @Override public void onSuccess(GameRequestDialog.Result result) { Log.d(TAG, "Success!"); Log.d(TAG, "Request id: " + result.getRequestId()); Log.d(TAG, "Recipients:"); for (String recipient : result.getRequestRecipients()) { Log.d(TAG, recipient); } } }); } @Override public void onResume() { super.onResume(); isResumed = true; } @Override public void onPause() { super.onPause(); isResumed = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RpsFragment.IN_APP_PURCHASE_RESULT) { String purchaseData = data.getStringExtra(INAPP_PURCHASE_DATA); if (resultCode == RESULT_OK) { RpsFragment fragment = (RpsFragment) fragments[RPS]; try { JSONObject jo = new JSONObject(purchaseData); fragment.onInAppPurchaseSuccess(jo); } catch (JSONException e) { Log.e(TAG, "In app purchase invalid json.", e); } } } } @Override public void onDestroy() { super.onDestroy(); accessTokenTracker.stopTracking(); } @Override protected void onResumeFragments() { super.onResumeFragments(); if (hasNativeLink) { showFragment(CONTENT, false); hasNativeLink = false; } else { showFragment(RPS, false); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only add the menu when the selection fragment is showing if (fragments[RPS].isVisible()) { if (menu.size() == 0) { share = menu.add(R.string.share_on_facebook); message = menu.add(R.string.send_with_messenger); challenge = menu.add(R.string.challenge_friends); settings = menu.add(R.string.check_settings); } return true; } else { menu.clear(); settings = null; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.equals(settings)) { showFragment(SETTINGS, true); return true; } else if (item.equals(challenge)) { GameRequestContent newGameRequestContent = new GameRequestContent.Builder() .setTitle(getString(R.string.challenge_dialog_title)) .setMessage(getString(R.string.challenge_dialog_message)) .build(); gameRequestDialog.show(this, newGameRequestContent); return true; } else if (item.equals(share)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingAutomaticDialog(); return true; } else if (item.equals(message)) { RpsFragment fragment = (RpsFragment) fragments[RPS]; fragment.shareUsingMessengerDialog(); return true; } return false; } private boolean handleNativeLink() { if (!AccessToken.isCurrentAccessTokenActive()) { AccessToken.createFromNativeLinkingIntent(getIntent(), FacebookSdk.getApplicationId(), new AccessToken.AccessTokenCreationCallback(){ @Override public void onSuccess(AccessToken token) { AccessToken.setCurrentAccessToken(token); } @Override public void onError(FacebookException error) { } }); } // See if we have a deep link in addition. int appLinkGesture = getAppLinkGesture(getIntent()); if (appLinkGesture != INVALID_CHOICE) { ContentFragment fragment = (ContentFragment) fragments[CONTENT]; fragment.setContentIndex(appLinkGesture); return true; } return false; } private int getAppLinkGesture(Intent intent) { Uri targetURI = AppLinks.getTargetUrlFromInboundIntent(this, intent); if (targetURI == null) { return INVALID_CHOICE; } String gesture = targetURI.getQueryParameter("gesture"); if (gesture != null) { if (gesture.equalsIgnoreCase(getString(R.string.rock))) { return RpsGameUtils.ROCK; } else if (gesture.equalsIgnoreCase(getString(R.string.paper))) { return RpsGameUtils.PAPER; } else if (gesture.equalsIgnoreCase(getString(R.string.scissors))) { return RpsGameUtils.SCISSORS; } } return INVALID_CHOICE; } void showFragment(int fragmentIndex, boolean addToBackStack) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (addToBackStack) { transaction.addToBackStack(null); } else { int backStackSize = fm.getBackStackEntryCount(); for (int i = 0; i < backStackSize; i++) { fm.popBackStack(); } } for (int i = 0; i < fragments.length; i++) { if (i == fragmentIndex) { transaction.show(fragments[i]); } else { transaction.hide(fragments[i]); } } transaction.commit(); } }
blob long method, data class t t f long method, data class blob 0 14371 https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/samples/RPSSample/src/com/example/rps/MainActivity.java/#L47-L287 1 2394 14371
693      { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } }
long method long method, data class t t t  data class   0 6654 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 1 693 6654
1232 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } }
blob data class, long method t t f data class, long method blob 0 10367 https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 1 1232 10367
3570  {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } }
blob blob, data class t t t  data class   0 7852 https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 1 3570 7852
726    { "response": "YES, I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 6846 https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 1 726 6846
1707  {"message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } }
blob data class t t f data class blob 0 11755 https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 1 1707 11755
419  { "response": "YES I found bad smells", "detected_bad_smells": { "1": "Long Method", "2": "Data Class" } } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BeamIntersectRel extends Intersect implements BeamRelNode { public BeamIntersectRel( RelOptCluster cluster, RelTraitSet traits, List inputs, boolean all) { super(cluster, traits, inputs, all); } @Override public SetOp copy(RelTraitSet traitSet, List inputs, boolean all) { return new BeamIntersectRel(getCluster(), traitSet, inputs, all); } @Override public PTransform, PCollection> buildPTransform() { return new BeamSetOperatorRelBase(this, BeamSetOperatorRelBase.OpType.INTERSECT, all); } }
blob 1: long method, 2: data class t t f 1: long method, 2: data class blob 0 4239 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamIntersectRel.java/#L37-L52 1 419 4239
233 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class NsTestPrintStream extends PrintStream { /////////////////////////////////////////////////////////////////////////////////// // // CONSTANTS // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // STATE // /////////////////////////////////////////////////////////////////////////////////// private boolean _chatty; /////////////////////////////////////////////////////////////////////////////////// // // CONSTRUCTOR // /////////////////////////////////////////////////////////////////////////////////// /** Construct a quiet or chatty print stream */ public NsTestPrintStream( PrintStream wrappedStream, boolean chatty ) { super( wrappedStream ); _chatty = chatty; } /////////////////////////////////////////////////////////////////////////////////// // // OVERRIDDEN BEHAVIOR // /////////////////////////////////////////////////////////////////////////////////// public PrintStream append( char c ) { if ( _chatty ) { super.append( c ); } return this; } public PrintStream append( CharSequence csq ) { if ( _chatty ) { super.append( csq ); } return this; } public PrintStream append( CharSequence csq, int start, int end ) { if ( _chatty ) { super.append( csq, start, end ); } return this; } public boolean checkError() { return super.checkError(); } protected void clearError() { super.clearError(); } public void close() { super.close(); } public void flush() { super.flush(); } public void print( boolean b ) { if ( _chatty ) { super.print( b ); } } public void print( char c ) { if ( _chatty ) { super.print( c ); } } public void print( int i ) { if ( _chatty ) { super.print( i ); } } public void print( long l ) { if ( _chatty ) { super.print( l ); } } public void print( float f ) { if ( _chatty ) { super.print( f ); } } public void print( double d ) { if ( _chatty ) { super.print( d ); } } public void print( char[] s ) { if ( _chatty ) { super.print( s ); } } public void print( String s ) { if ( _chatty ) { super.print( s ); } } public void print( Object obj ) { if ( _chatty ) { super.print( obj ); } } public void println() { if ( _chatty ) { super.println(); } } public void println( boolean x ) { if ( _chatty ) { super.println( x ); } } public void println( char x ) { if ( _chatty ) { super.println( x ); } } public void println( int x ) { if ( _chatty ) { super.println( x ); } } public void println( long x ) { if ( _chatty ) { super.println( x ); } } public void println( float x ) { if ( _chatty ) { super.println( x ); } } public void println( double x ) { if ( _chatty ) { super.println( x ); } } public void println( char[] x ) { if ( _chatty ) { super.println( x ); } } public void println( String x ) { if ( _chatty ) { super.println( x ); } } public void println( Object x ) { if ( _chatty ) { super.println( x ); } } public PrintStream printf( String format, Object... args ) { if ( _chatty ) { super.printf( format, args ); } return this; } public PrintStream printf( Locale l, String format, Object... args ) { if ( _chatty ) { super.printf( l, format, args ); } return this; } public PrintStream format( String format, Object... args ) { if ( _chatty ) { super.format( format, args ); } return this; } public PrintStream format( Locale l, String format, Object... args ) { if ( _chatty ) { super.format( l, format, args ); } return this; } public void write( byte[] buf, int off, int len ) { if ( _chatty ) { super.write( buf, off, len ); } } public void write( int b ) { if ( _chatty ) { super.write( b ); } } }
blob data class t t f data class blob 0 2549 https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.tests/org/apache/derbyTesting/system/nstest/NsTestPrintStream.java/#L31-L127 1 233 2549
1534  { "output": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ImportsAwareClipboardAction extends TextEditorAction { public static class Factory implements IClipboardActionFactory { @Inject private MembersInjector injector; @Override public TextEditorAction create(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) { ImportsAwareClipboardAction action = new ImportsAwareClipboardAction(bundle, prefix, editor, operationCode); injector.injectMembers(action); return action; } } private static final XbaseClipboardTransfer TRANSFER_INSTANCE = new XbaseClipboardTransfer(); private final int operationCode; private ITextOperationTarget textOperationTarget; private @Inject ImportsUtil importsUtil; /** * Creates the action. * * @param bundle * the resource bundle * @param prefix * a prefix to be prepended to the various resource keys (described in ResourceAction * constructor), or null if none * @param editor * the text editor. May not be null. * @param operationCode * the operation code */ public ImportsAwareClipboardAction(ResourceBundle bundle, String prefix, ITextEditor editor, final int operationCode) { super(bundle, prefix, editor); this.operationCode = operationCode; if (operationCode == ITextOperationTarget.CUT) { setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); } else if (operationCode == ITextOperationTarget.COPY) { setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); } else if (operationCode == ITextOperationTarget.PASTE) { setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); } else { Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$ } update(); } protected void internalDoOperation() { if (operationCode == ITextOperationTarget.PASTE) { doPasteWithImportsOperation(); } else { doCutCopyWithImportsOperation(); } } private void doCutCopyWithImportsOperation() { try { final XbaseClipboardData cbData = createClipboardData(); if (cbData != null ) { ClipboardUtil.clipboardOperation(new Function() { @Override public Boolean apply(Clipboard clipboard) { Map payload = newLinkedHashMap(); payload.put(cbData, TRANSFER_INSTANCE); TextTransfer textTransfer = TextTransfer.getInstance(); String textData = (String) clipboard.getContents(textTransfer); if (textData == null || textData.isEmpty()) { // StyledText copied any data to ClipBoard return Boolean.FALSE; } payload.put(textData, textTransfer); RTFTransfer rtfTransfer = RTFTransfer.getInstance(); String rtfData = (String) clipboard.getContents(rtfTransfer); if (rtfData != null && !rtfData.isEmpty()) { payload.put(rtfData, rtfTransfer); } List datas = newArrayList(); List dataTypes = newArrayList(); for (Entry entry : payload.entrySet()) { datas.add(entry.getKey()); dataTypes.add(entry.getValue()); } try { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) { clipboard.setContents(datas.toArray(), dataTypes.toArray(new Transfer[] {})); return Boolean.TRUE; } return Boolean.FALSE; } } }); } } finally { textOperationTarget.doOperation(operationCode); } } private void doPasteWithImportsOperation() { XbaseClipboardData xbaseClipboardData = ClipboardUtil .clipboardOperation(new Function() { @Override public XbaseClipboardData apply(Clipboard input) { Object content = input.getContents(TRANSFER_INSTANCE); if (content instanceof XbaseClipboardData) { return (XbaseClipboardData) content; } return null; } }); JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent(); String textFromClipboard = ClipboardUtil.getTextFromClipboard(); XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor)); if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) { doPasteXbaseCode(xbaseClipboardData, addImports); } else if (javaImportsContent != null) { doPasteJavaCode(textFromClipboard, javaImportsContent, addImports); } else { textOperationTarget.doOperation(operationCode); } } /** * Should not add imports when pasting into a {@link XStringLiteral} or Comments (except of JavaDoc) * * @param document * - {@link IDocument} to work with * @param caretOffset * - current caret offset */ protected boolean shouldAddImports(IDocument document, int caretOffset) { if (caretOffset == 0) { return true; } String typeRight = IDocument.DEFAULT_CONTENT_TYPE; String typeLeft = IDocument.DEFAULT_CONTENT_TYPE; try { typeRight = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset, false); typeLeft = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, caretOffset > 0 ? caretOffset - 1 : caretOffset, false); } catch (BadLocationException exception) { // Should not happen } if (COMMENT_PARTITION.equals(typeRight) || STRING_LITERAL_PARTITION.equals(typeRight) || SL_COMMENT_PARTITION.equals(typeRight) || "__rich_string".equals(typeRight)) { if (typeLeft.equals(typeRight)) return false; } return true; } private int caretOffset(final XtextEditor xtextEditor) { ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer(); int caretOffset = sourceViewer.getTextWidget().getCaretOffset(); if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; caretOffset = extension.widgetOffset2ModelOffset(caretOffset); } return caretOffset; } private void doPasteXbaseCode(XbaseClipboardData xbaseClipboardData, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(xbaseClipboardData.getImports(), xbaseClipboardData.getStaticImports(), xbaseClipboardData.getExtensionImports(), getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private void doPasteJavaCode(String textFromClipboard, JavaImportData javaImportsContent, boolean withImports) { IRewriteTarget target = getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { textOperationTarget.doOperation(operationCode); if (withImports) { importsUtil.addImports(javaImportsContent.getImports(), javaImportsContent.getStaticImports(), new String[] {}, getXtextDocument()); } } catch (Exception e) { XbaseActivator.getInstance().getLog().log(new Status(IStatus.ERROR, XbaseActivator.getInstance().getBundle().getSymbolicName(), "Unexpected internal error: ", e)); } finally { if (target != null) { target.endCompoundChange(); } } } private boolean sameTarget(XbaseClipboardData xbaseClipboardData) { IEditorInput editorInput = getTextEditor().getEditorInput(); if (editorInput == null) { return false; } return xbaseClipboardData.getSourceIndentifier().equals(editorInput.toString()); } private XbaseClipboardData createClipboardData() { try { IEditorInput editorInput = getTextEditor().getEditorInput(); final String sourceIdentifier = editorInput != null ? editorInput.toString() : "nullEditorInput"; IXtextDocument document = getXtextDocument(); final ISelection selection = getTextEditor().getSelectionProvider().getSelection(); if (selection instanceof ITextSelection && !selection.isEmpty()) { final ITextSelection textSelection = (ITextSelection) selection; return document.readOnly(new IUnitOfWork() { @Override public XbaseClipboardData exec(XtextResource state) throws Exception { ITextRegion region = new TextRegion(textSelection.getOffset(), textSelection.getLength() - 1); Triple, Set, Set> imports = importsUtil.collectImports(state, region); XbaseClipboardData clipboardData = new XbaseClipboardData(sourceIdentifier, Iterables.toArray(imports.getFirst(), String.class), Iterables.toArray(imports.getSecond(), String.class), Iterables.toArray(imports.getThird(), String.class)); return clipboardData; } }); } } catch (Exception e) { //TODO Log exception return null; } return null; } private IXtextDocument getXtextDocument() { XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor()); IXtextDocument document = xtextEditor.getDocument(); return document; } @Override public void update() { super.update(); if (isModifyOperation() && !canModifyEditor()) { setEnabled(false); return; } ITextEditor editor = getTextEditor(); if (textOperationTarget == null && editor != null) textOperationTarget = editor.getAdapter(ITextOperationTarget.class); boolean isEnabled = (textOperationTarget != null && textOperationTarget.canDoOperation(getOperationCode())); setEnabled(isEnabled); } private int getOperationCode() { return operationCode; } @Override public void run() { if (textOperationTarget == null) return; ITextEditor editor = getTextEditor(); if (editor == null) return; if (isModifyOperation() && !validateEditorInputState()) return; BusyIndicator.showWhile(getDisplay(), new Runnable() { @Override public void run() { internalDoOperation(); } }); } private boolean isModifyOperation() { return operationCode != ITextOperationTarget.COPY; } private Shell getShell() { ITextEditor editor = getTextEditor(); if (editor != null) { IWorkbenchPartSite site = editor.getSite(); Shell shell = site.getShell(); if (shell != null && !shell.isDisposed()) { return shell; } } return null; } private Display getDisplay() { Shell shell = getShell(); if (shell != null) { return shell.getDisplay(); } return null; } @Override public void setEditor(ITextEditor editor) { super.setEditor(editor); this.textOperationTarget = null; } public static final class XbaseClipboardData { private String sourceIndentifier; private String[] imports; private String[] staticImports; private String[] extensionImports; public XbaseClipboardData(String sourceIndentifier, String[] imports, String[] staticImports, String[] extensionImports) { this.sourceIndentifier = sourceIndentifier; this.imports = imports; this.staticImports = staticImports; this.extensionImports = extensionImports; } public XbaseClipboardData(byte[] bytes) throws IOException { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes)); try { sourceIndentifier = dataIn.readUTF(); imports = readArray(dataIn); staticImports = readArray(dataIn); extensionImports = readArray(dataIn); } finally { dataIn.close(); } } protected final String[] readArray(DataInputStream dataIn) throws IOException { int count = dataIn.readInt(); String[] array = new String[count]; for (int i = 0; i < count; i++) { array[i] = dataIn.readUTF(); } return array; } public byte[] serialize() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); try { dataOut.writeUTF(sourceIndentifier); writeArray(dataOut, imports); writeArray(dataOut, staticImports); writeArray(dataOut, extensionImports); } finally { dataOut.close(); out.close(); } return out.toByteArray(); } protected final void writeArray(DataOutputStream dataOut, String[] array) throws IOException { dataOut.writeInt(array.length); for (int i = 0; i < array.length; i++) { dataOut.writeUTF(array[i]); } } public String getSourceIndentifier() { return sourceIndentifier; } public String[] getImports() { return imports; } public String[] getStaticImports() { return staticImports; } public String[] getExtensionImports() { return extensionImports; } } private static class XbaseClipboardTransfer extends ByteArrayTransfer { private static final String TYPE_NAME = "xbase-source-with-imports-transfer-format"; private static final int TYPEID = registerType(TYPE_NAME); @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @Override protected void javaToNative(Object data, TransferData transferData) { if (data instanceof XbaseClipboardData) { try { super.javaToNative(((XbaseClipboardData) data).serialize(), transferData); } catch (IOException e) { //it's best to send nothing if there were problems } } } @Override protected Object nativeToJava(TransferData transferData) { byte[] bytes = (byte[]) super.nativeToJava(transferData); if (bytes != null) { try { return new XbaseClipboardData(bytes); } catch (IOException e) { } } return null; } } }
blob data class, long method t t f data class, long method blob 0 11212 https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.xbase.ui/src/org/eclipse/xtext/xbase/ui/editor/actions/ImportsAwareClipboardAction.java/#L79-L520 1 1534 11212
1538 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; }
long method Long Method, Data Class t f t  Data Class   0 11226 https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 1 1538 11226
5490   YES I found bad smells. the bad smells are: 1. Long method, 2. Data class. The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; }
long method  Long method, 2 Data class t f t  2. Data class.   0 1877 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 1 5490 1877
1673      { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } }
blob blob, data class, long method t t t  data class, long method   0 11642 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 1 1673 11642
712 ; YES I found bad smells The bad smells are: 1. Long method 2. Feature envy: method isAuthorized() 3. Feature envy: method getMessageConverters() 4. Primitive obsession: multiple variable declarations and assignments for message converters 5. Data clumps: multiple variables related to HTTP message converters 6. Message chain: multiple method calls on restTemplate and converter objects 7. Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data 8. Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters() 9. Data clumps: multiple variables related to access tokens and token strategies 10. Shotgun surgery: any changes to methods or constructors could require changing multiple methods/classes. 11. Lazy class: method postConstructionConfiguration() does not have a default behavior and is not used in the class. 12. Long parameter list: constructor for method createRestTemplate() has multiple parameters. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } }
blob  Long method2 Feature envy: method isAuthorized()3 Feature envy: method getMessageConverters()4 Primitive obsession: multiple variable declarations and assignments for message converters5 Data clumps: multiple variables related to HTTP message converters6 Message chain: multiple method calls on restTemplate and converter objects7 Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data8 Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters()9 Data clumps: multiple variables related to access tokens and token strategies t f f . Long method2. Feature envy: method isAuthorized()3. Feature envy: method getMessageConverters()4. Primitive obsession: multiple variable declarations and assignments for message converters5. Data clumps: multiple variables related to HTTP message converters6. Message chain: multiple method calls on restTemplate and converter objects7. Data class: AbstractOAuth2ApiBinding class has no behavior and only contains data8. Duplicated code: method createRestTemplateWithCulledMessageConverters() has similar logic to method getMessageConverters()9. Data clumps: multiple variables related to access tokens and token strategies blob 0 6781 https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 2 712 6781
655 {"response":"YES I found bad smells","bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } }
blob long method, data class t t f long method, data class blob 0 6404 https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 1 655 6404
2450                                                                                                                 { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; }
long method long method, data class t t t  data class   0 14505 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 1 2450 14505
2039   YES I found bad smells the bad smells are: 1.Long method, 2.Long class, 3.Improper exception handling, 4.Magic numbers, 5.Unnecessary comments, 6.Inconsistent naming conventions, 7.Redundant code, 8.Feature envy, 9.Data class, 10.Inappropriate identifiers I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } }
blob Long method, 2Long class, 3Improper exception handling, 4Magic numbers, 5Unnecessary comments, 6Inconsistent naming conventions, 7Redundant code, 8Feature envy, 9Data class, t f f .Long method, 2.Long class, 3.Improper exception handling, 4.Magic numbers, 5.Unnecessary comments, 6.Inconsistent naming conventions, 7.Redundant code, 8.Feature envy, 9.Data class, blob 0 12844 https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 2 2039 12844
3933 { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); }
feature envy long method, data class t t f long method, data class feature envy 0 10289 https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 1 3933 10289
1888  { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } }
blob long method, data class t t f long method, data class blob 0 12300 https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 1 1888 12300
1661 { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class NetAgent extends Agent { //---------------------navigational members----------------------------------- // All these request objects point to the same physical request object. ConnectionRequestInterface connectionRequest_; StatementRequestInterface statementRequest_; ResultSetRequestInterface resultSetRequest_; // All these reply objects point to the same physical reply object. ConnectionReply connectionReply_; private ConnectionReply packageReply_; StatementReply statementReply_; ResultSetReply resultSetReply_; //---------------------navigational cheat-links------------------------------- // Cheat-links are for convenience only, and are not part of the conceptual model. // Warning: // Cheat-links should only be defined for invariant state data. // That is, the state data is set by the constructor and never changes. // Alias for (NetConnection) super.connection NetConnection netConnection_; // Alias for (Request) super.*Request, all in one // In the case of the NET implementation, these all point to the same physical request object. private Request request_; NetConnectionRequest netConnectionRequest_; private NetPackageRequest netPackageRequest_; private NetStatementRequest netStatementRequest_; private NetResultSetRequest netResultSetRequest_; // Alias for (Reply) super.*Reply, all in one. // In the case of the NET implementation, these all point to the same physical reply object. private Reply reply_; NetConnectionReply netConnectionReply_; private NetPackageReply netPackageReply_; private NetStatementReply netStatementReply_; private NetResultSetReply netResultSetReply_; //-----------------------------state------------------------------------------ Socket socket_; private InputStream rawSocketInputStream_; private OutputStream rawSocketOutputStream_; String server_; int port_; private int clientSSLMode_; private EbcdicCcsidManager ebcdicCcsidManager_; private Utf8CcsidManager utf8CcsidManager_; private CcsidManager currentCcsidManager_; // TODO: Remove target? Keep just one CcsidManager? //public CcsidManager targetCcsidManager_; Typdef typdef_; Typdef targetTypdef_; Typdef originalTargetTypdef_; // added to support typdef overrides private int svrcod_; int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7; int targetSqlam_ = orignalTargetSqlam_; SqlException exceptionOpeningSocket_ = null; SqlException exceptionConvertingRdbnam = null; /** * Flag which indicates that a writeChain has been started and data sent to * the server. * If true, starting a new write chain will throw a DisconnectException. * It is cleared when the write chain is ended. */ private boolean writeChainIsDirty_ = false; //---------------------constructors/finalizer--------------------------------- // Only used for testing public NetAgent(NetConnection netConnection, LogWriter logWriter) throws SqlException { super(netConnection, logWriter); this.netConnection_ = netConnection; } NetAgent(NetConnection netConnection, LogWriter netLogWriter, int loginTimeout, String server, int port, int clientSSLMode) throws SqlException { super(netConnection, netLogWriter); server_ = server; port_ = port; netConnection_ = netConnection; clientSSLMode_ = clientSSLMode; if (server_ == null) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET), "serverName"); } try { socket_ = (Socket)AccessController.doPrivileged( new OpenSocketAction(server, port, clientSSLMode_)); } catch (PrivilegedActionException e) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER), e.getException(), e.getException().getClass().getName(), server, port, e.getException().getMessage()); } // Set TCP/IP Socket Properties try { if (exceptionOpeningSocket_ == null) { socket_.setTcpNoDelay(true); // disables nagles algorithm socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2 socket_.setSoTimeout(loginTimeout * 1000); } } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION), e, e.getMessage()); } try { if (exceptionOpeningSocket_ == null) { rawSocketOutputStream_ = socket_.getOutputStream(); rawSocketInputStream_ = socket_.getInputStream(); } } catch (IOException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM), e, e.getMessage()); } ebcdicCcsidManager_ = new EbcdicCcsidManager(); utf8CcsidManager_ = new Utf8CcsidManager(); currentCcsidManager_ = ebcdicCcsidManager_; if (netConnection_.isXAConnection()) { NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_); netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_; netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, netConnection_.commBufferSize_); netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_; netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } else { netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_); netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; netResultSetRequest_ = new NetResultSetRequest(this, netConnection_.commBufferSize_); netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } } protected void resetAgent_(LogWriter netLogWriter, //CcsidManager sourceCcsidManager, //CcsidManager targetCcsidManager, int loginTimeout, String server, int port) throws SqlException { exceptionConvertingRdbnam = null; // most properties will remain unchanged on connect reset. targetTypdef_ = originalTargetTypdef_; svrcod_ = 0; // Set TCP/IP Socket Properties try { socket_.setSoTimeout(loginTimeout * 1000); } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } throw new SqlException(logWriter_, new ClientMessageId(SQLState.SOCKET_EXCEPTION), e, e.getMessage()); } } void setSvrcod(int svrcod) { if (svrcod > svrcod_) { svrcod_ = svrcod; } } void clearSvrcod() { svrcod_ = CodePoint.SVRCOD_INFO; } private int getSvrcod() { return svrcod_; } public void flush_() throws DisconnectException { sendRequest(); reply_.initialize(); } // Close socket and its streams. public void close_() throws SqlException { // can we just close the socket here, do we need to close streams individually SqlException accumulatedExceptions = null; if (rawSocketInputStream_ != null) { try { rawSocketInputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes accumulatedExceptions = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); } finally { rawSocketInputStream_ = null; } } if (rawSocketOutputStream_ != null) { try { rawSocketOutputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { rawSocketOutputStream_ = null; } } if (socket_ != null) { try { socket_.close(); } catch (IOException e) { // again {6} = 0, indicates the socket was closed. // maybe set {4} to e.getMessage(). // do this for now and but may need to modify or // add this to the message pubs. SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { socket_ = null; } } if (accumulatedExceptions != null) { throw accumulatedExceptions; } } /** * Specifies the maximum blocking time that should be used when sending * and receiving messages. The timeout is implemented by using the the * underlying socket implementation's timeout support. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @param timeout The timeout value in seconds. A value of 0 corresponds to * infinite timeout. */ protected void setTimeout(int timeout) { try { // Sets a timeout on the socket socket_.setSoTimeout(timeout * 1000); // convert to milliseconds } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.setTimeout: ignoring exception: " + se); } } } /** * Returns the current timeout value that is set on the socket. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @return The timeout value in seconds. A value of 0 corresponds to * that no timeout is specified on the socket. */ protected int getTimeout() { int timeout = 0; // 0 is default timeout for sockets // Read the timeout currently set on the socket try { timeout = socket_.getSoTimeout(); } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.getTimeout: ignoring exception: " + se); } } // Convert from milliseconds to seconds (note that this truncates // the results towards zero but that should not be a problem). timeout = timeout / 1000; return timeout; } private void sendRequest() throws DisconnectException { try { request_.flush(rawSocketOutputStream_); } catch (IOException e) { throwCommunicationsFailure(e); } } public InputStream getInputStream() { return rawSocketInputStream_; } public CcsidManager getCurrentCcsidManager() { return currentCcsidManager_; } public OutputStream getOutputStream() { return rawSocketOutputStream_; } void setInputStream(InputStream inputStream) { rawSocketInputStream_ = inputStream; } void setOutputStream(OutputStream outputStream) { rawSocketOutputStream_ = outputStream; } void throwCommunicationsFailure(Throwable cause) throws DisconnectException { //DisconnectException //accumulateReadExceptionAndDisconnect // note when {6} = 0 it indicates the socket was closed. // need to still validate any token values against message publications. accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(this, new ClientMessageId(SQLState.COMMUNICATION_ERROR), cause, cause.getMessage())); } // ----------------------- call-down methods --------------------------------- protected void markChainBreakingException_() { setSvrcod(CodePoint.SVRCOD_ERROR); } public void checkForChainBreakingException_() throws SqlException { int svrcod = getSvrcod(); clearSvrcod(); if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker { super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one. } } private void writeDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.writeDeferredReset(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } /** * Marks the agent's write chain as dirty. A write chain is dirty when data * from it has been sent to the server. A dirty write chain cannot be reset * and reused for another request until the remaining data has been sent to * the server and the write chain properly ended. * * Resetting a dirty chain will cause the new request to be appended to the * unfinished request already at the server, which will likely lead to * cryptic syntax errors. */ void markWriteChainAsDirty() { writeChainIsDirty_ = true; } private void verifyWriteChainIsClean() throws DisconnectException { if (writeChainIsDirty_) { throw new DisconnectException(this, new ClientMessageId(SQLState.NET_WRITE_CHAIN_IS_DIRTY)); } } public void beginWriteChainOutsideUOW() throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); } public void beginWriteChain(ClientStatement statement) throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); super.beginWriteChain(statement); } protected void endWriteChain() {} private void readDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.readDeferredReset(); checkForExceptions(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } protected void beginReadChain(ClientStatement statement) throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChain(statement); } protected void beginReadChainOutsideUOW() throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChainOutsideUOW(); } /** * Switches the current CCSID manager to UTF-8 */ void switchToUtf8CcsidMgr() { currentCcsidManager_ = utf8CcsidManager_; } /** * Switches the current CCSID manager to EBCDIC */ void switchToEbcdicMgr() { currentCcsidManager_ = ebcdicCcsidManager_; } }
blob blob, data class t t t  data class   0 11610 https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.client/org/apache/derby/client/net/NetAgent.java/#L43-L550 1 1661 11610
601  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("deprecation") public class MRBaseForCommonInstructions extends MapReduceBase { //indicate whether the matrix value in this mapper is a matrix cell or a matrix block protected Class valueClass; //a cache to hold the intermediate results protected CachedValueMap cachedValues=new CachedValueMap(); //distributed cache data handling public static boolean isJobLocal = false; //set from MapperBase public static HashMap dcValues = new HashMap<>(); protected HashMap dimensions=new HashMap<>(); //temporary variables protected IndexedMatrixValue tempValue=null; protected IndexedMatrixValue zeroInput=null; @Override public void configure(JobConf job) { //whether to use the cell representation or the block representation valueClass=MRJobConfiguration.getMatrixValueClass(job); //allocate space for temporary variables tempValue=new IndexedMatrixValue(valueClass); zeroInput=new IndexedMatrixValue(valueClass); //matrix characteristics inputs/outputs byte[] inputIX = MRJobConfiguration.getInputIndexesInMapper(job); for( byte ix : inputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForInput(job, ix)); byte[] mapOutputIX = MRJobConfiguration.getOutputIndexesInMapper(job); for(byte ix : mapOutputIX) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForMapOutput(job, ix)); byte[] outputIX = MRJobConfiguration.getResultIndexes(job); for( byte ix : outputIX ) dimensions.put(ix, MRJobConfiguration.getMatrixCharacteristicsForOutput(job, ix)); //matrix characteristics intermediates byte[] immediateIndexes=MRJobConfiguration.getIntermediateMatrixIndexes(job); if(immediateIndexes!=null) { for(byte index: immediateIndexes) dimensions.put(index, MRJobConfiguration.getIntermediateMatrixCharactristics(job, index)); } } protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value, int i, Reporter reporter, CollectMultipleConvertedOutputs collectFinalMultipleOutputs, byte[] resultDimsUnknown, long[] resultsNonZeros, long[] resultsMaxRowDims, long[] resultsMaxColDims) throws IOException { collectFinalMultipleOutputs.collectOutput(indexes, value, i, reporter); resultsNonZeros[i]+=value.getNonZeros(); if ( resultDimsUnknown[i] == (byte) 1 ) { // compute dimensions for the resulting matrix // find the maximum row index and column index encountered in current output block/cell long maxrow = getMaxDimension(indexes, value, true); long maxcol = getMaxDimension(indexes, value, false); if ( maxrow > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = maxrow; if ( maxcol > resultsMaxColDims[i] ) resultsMaxColDims[i] = maxcol; } else if(resultDimsUnknown[i] == (byte) 2) { if ( indexes.getRowIndex() > resultsMaxRowDims[i] ) resultsMaxRowDims[i] = indexes.getRowIndex(); if ( indexes.getColumnIndex() > resultsMaxColDims[i] ) resultsMaxColDims[i] = indexes.getColumnIndex(); } } protected void processMixedInstructions(ArrayList mixed_instructions) { if( mixed_instructions != null ) for( MRInstruction ins : mixed_instructions ) processOneInstruction(ins, valueClass, cachedValues, tempValue, zeroInput); } protected void processOneInstruction(MRInstruction ins, Class valueClass, CachedValueMap cachedValues, IndexedMatrixValue tempValue, IndexedMatrixValue zeroInput) { //Timing time = new Timing(true); if ( ins instanceof AggregateBinaryInstruction ) { byte input = ((AggregateBinaryInstruction)ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof ZeroOutInstruction || ins instanceof AggregateUnaryInstruction || ins instanceof RangeBasedReIndexInstruction || ins instanceof CumulativeSplitInstruction) { byte input=((UnaryMRInstructionBase) ins).input; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); if( ins instanceof CumulativeAggregateInstruction ) ((CumulativeAggregateInstruction)ins).setMatrixCharacteristics(dim); if( ins instanceof CumulativeSplitInstruction ) ((CumulativeSplitInstruction)ins).setMatrixCharacteristics(dim); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof ReorgInstruction ) { ReorgInstruction rinst = (ReorgInstruction) ins; byte input = rinst.input; MatrixCharacteristics dim = dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); rinst.setInputMatrixCharacteristics(dim); rinst.setOutputEmptyBlocks(!(this instanceof MMCJMRMapper)); //MMCJMRMapper does not output empty blocks, no need to generate ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if( ins instanceof MatrixReshapeMRInstruction ) { MatrixReshapeMRInstruction mrins = (MatrixReshapeMRInstruction) ins; byte input = mrins.input; byte output = mrins.output; MatrixCharacteristics dimIn=dimensions.get(input); MatrixCharacteristics dimOut=dimensions.get(output); if(dimIn==null || dimOut==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); mrins.setMatrixCharacteristics(dimIn, dimOut); mrins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof AppendMInstruction) { byte input=((AppendMInstruction) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof BinaryMInstruction || ins instanceof RemoveEmptyMRInstruction ) { byte input=((BinaryMRInstructionBase) ins).input1; MatrixCharacteristics dim=dimensions.get(input); if(dim==null) throw new DMLRuntimeException("dimension for instruction "+ins+" is unset!!!"); ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dim.getRowsPerBlock(), dim.getColsPerBlock()); } else if(ins instanceof AppendGInstruction) { AppendGInstruction arinst = ((AppendGInstruction) ins); byte input = arinst.input1; MatrixCharacteristics dimIn=dimensions.get(input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+arinst+" is unset!!!"); arinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof UnaryMRInstructionBase) { UnaryMRInstructionBase rinst = (UnaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input); if( dimIn==null ) throw new DMLRuntimeException("Dimensions for instruction "+rinst+" is unset!!!"); rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); } else if(ins instanceof BinaryMRInstructionBase) { BinaryMRInstructionBase rinst = (BinaryMRInstructionBase) ins; MatrixCharacteristics dimIn=dimensions.get(rinst.input1); if( dimIn!=null ) //not set for all rinst.processInstruction(valueClass, cachedValues, tempValue, zeroInput, dimIn.getRowsPerBlock(), dimIn.getColsPerBlock()); else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); } else ins.processInstruction(valueClass, cachedValues, tempValue, zeroInput, -1, -1); //System.out.println(ins.getMRInstructionType()+" in "+time.stop()); } /** * Reset in-memory state from distributed cache (required only for * local job runner) */ public static void resetDistCache() { for(DistributedCacheInput dcInput : dcValues.values() ) dcInput.reset(); dcValues.clear(); } protected void setupDistCacheFiles(JobConf job) throws IOException { if ( MRJobConfiguration.getDistCacheInputIndices(job) == null ) return; //boolean isJobLocal = false; isJobLocal = InfrastructureAnalyzer.isLocalMode(job); String[] inputIndices = MRJobConfiguration.getInputPaths(job); String[] dcIndices = MRJobConfiguration.getDistCacheInputIndices(job).split(Instruction.INSTRUCTION_DELIM); Path[] dcFiles = DistributedCache.getLocalCacheFiles(job); PDataPartitionFormat[] inputPartitionFormats = MRJobConfiguration.getInputPartitionFormats(job); DistributedCacheInput[] dcInputs = new DistributedCacheInput[dcIndices.length]; for(int i=0; i < dcIndices.length; i++) { byte inputIndex = Byte.parseByte(dcIndices[i]); //load if not already present (jvm reuse) if( !dcValues.containsKey(inputIndex) ) { // When the job is in local mode, files can be read from HDFS directly -- use // input paths as opposed to "local" paths prepared by DistributedCache. Path p = null; if(isJobLocal) p = new Path(inputIndices[ Byte.parseByte(dcIndices[i]) ]); else p = dcFiles[i]; dcInputs[i] = new DistributedCacheInput( p, MRJobConfiguration.getNumRows(job, inputIndex), //rlens[inputIndex], MRJobConfiguration.getNumColumns(job, inputIndex), //clens[inputIndex], MRJobConfiguration.getNumRowsPerBlock(job, inputIndex), //brlens[inputIndex], MRJobConfiguration.getNumColumnsPerBlock(job, inputIndex), //bclens[inputIndex], inputPartitionFormats[inputIndex] ); dcValues.put(inputIndex, dcInputs[i]); } } } /** * Returns the maximum row or column dimension of the given key and value pair. * * @param key matrix indexes * @param value MatrixValue of either type MatrixCell or MatrixBlock * @param row if true return row dimension, else return column dimension * @return maximum row or column dimension, or 0 if MatrixValue not MatrixCell or MatrixBlock */ private static long getMaxDimension( MatrixIndexes key, MatrixValue value, boolean row ) { if( value instanceof MatrixCell ) return row ? key.getRowIndex() : key.getColumnIndex(); else if( value instanceof MatrixBlock ) return row ? value.getNumRows() : value.getNumColumns(); return 0; } }
blob long method, data class t t f long method, data class blob 0 5994 https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/matrix/mapred/MRBaseForCommonInstructions.java/#L58-L311 1 601 5994
2365   YES, I found bad smells. The bad smells are: 1.Long method, 2.Feature envy, 3.Inappropriate intimacy, 4.Magic numbers, 5.Message chains, 6.Long parameter list, 7.Data clump, 8.Switch statements, 9.Data class, 10.Long class, 11.Incomplete library class, 12.Multiple return statements, 13.Lazy class. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } }
blob Long method, 2Feature envy, 3Inappropriate intimacy, 4Magic numbers, 5Message chains, 6Long parameter list, 7Data clump, 8Switch statements, 9Data class, t f f .Long method, 2.Feature envy, 3.Inappropriate intimacy, 4.Magic numbers, 5.Message chains, 6.Long parameter list, 7.Data clump, 8.Switch statements, 9.Data class, blob 0 14259 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 2 2365 14259
1657    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; }
long method Long Method, Data Class t f t  Data Class   0 11601 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 1 1657 11601
1151 { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); }
blob long method, data class t t f long method, data class blob 0 10132 https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 1 1151 10132
586 { "response": "YES I found bad smells", "bad smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob long method, data class t t f long method, data class blob 0 5819 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/protocol/src/main/java/org/apache/drill/exec/proto/UserProtos.java/#L19445-L20118 1 586 5819
1236 {"result":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class EventAdapterGenerator { public static AdapterClassLoader ldr = new AdapterClassLoader(); static Class EVENTLISTENER = null; static String CLASSPACKAGE = "org/apache/bsf/util/event/adapters/"; static String WRITEDIRECTORY = null; // starting 8 bytes of all Java Class files static byte CLASSHEADER[]; // constant pool items found in all event adapters static short BASECPCOUNT; // number of cp items + 1 ( cp item # 0 reserved for JVM ) static byte BASECP[]; // // some bytes in the middle of the class file (see below) static byte FIXEDCLASSBYTES[]; // the initialization method, noargs constructor static byte INITMETHOD[]; private static BSF_Log logger=null; /* The static initializer */ static { // logger = LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); logger = BSF_LogFactory.getLog((org.apache.bsf.util.event.generator.EventAdapterGenerator.class).getName()); String USERCLASSPACKAGE = System.getProperty("DynamicEventClassPackage", ""); if (!USERCLASSPACKAGE.equals("")) { CLASSPACKAGE = USERCLASSPACKAGE; } if(CLASSPACKAGE.length() > 0 ) { CLASSPACKAGE = CLASSPACKAGE.replace('\\','/'); if(!CLASSPACKAGE.endsWith("/")) { CLASSPACKAGE = CLASSPACKAGE+"/"; } } WRITEDIRECTORY = System.getProperty("DynamicEventClassWriteDirectory",CLASSPACKAGE); if(WRITEDIRECTORY.length() > 0 ) { WRITEDIRECTORY = WRITEDIRECTORY.replace('\\','/'); if(!WRITEDIRECTORY.endsWith("/")) { WRITEDIRECTORY = WRITEDIRECTORY+"/"; } } try // { EVENTLISTENER = Class.forName("java.util.EventListener"); } { // EVENTLISTENER = Thread.currentThread().getContextClassLoader().loadClass ("java.util.EventListener"); // rgf, 2006-01-05 // rgf, 20070917: first try context class loader, then BSFManager's defining class loader EVENTLISTENER=null; ClassLoader tccl=Thread.currentThread().getContextClassLoader(); if (tccl!=null) { try { EVENTLISTENER = tccl.loadClass ("java.util.EventListener"); } catch(ClassNotFoundException ex01) {} } if (EVENTLISTENER==null) // did not work, try to load it via the definedClassLoader { EVENTLISTENER = BSFManager.getDefinedClassLoader().loadClass ("java.util.EventListener"); } } catch(ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // start of the Java Class File CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xCA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xFE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBA); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(byte)0xBE); // magic CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)3); // minor version CLASSHEADER = ByteUtility.addBytes(CLASSHEADER,(short)45); // major version // Start the constant pool for base items in all event adapter classes BASECPCOUNT = 17; // number of cp items + 1 ( cp item # 0 reserved for JVM ) // cp item 01 BASECP = Bytecode.addUtf8(BASECP,"()V"); // cp item 02 BASECP = Bytecode.addUtf8(BASECP,""); // cp item 03 BASECP = Bytecode.addUtf8(BASECP,"Code"); // cp item 04 BASECP = Bytecode.addUtf8(BASECP,"eventProcessor"); // cp item 05 BASECP = Bytecode.addUtf8(BASECP,"java/lang/Object"); // cp item 06 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventAdapterImpl"); // cp item 07 BASECP = Bytecode.addUtf8(BASECP,"org/apache/bsf/util/event/EventProcessor"); // cp item 08 BASECP = Bytecode.addUtf8(BASECP,"(Ljava/lang/String;[Ljava/lang/Object;)V"); // cp item 09 BASECP = Bytecode.addUtf8(BASECP,"Lorg/apache/bsf/util/event/EventProcessor;"); // cp item 10 BASECP = Bytecode.addClass(BASECP,(short)5); // Class "java/lang/Object" // cp item 11 BASECP = Bytecode.addClass(BASECP,(short)6); // Class "org/apache/bsf/util/event/EventAdapterImpl" // cp item 12 BASECP = Bytecode.addClass(BASECP,(short)7); // Class "org/apache/bsf/util/event/EventProcessor" // cp item 13 BASECP = Bytecode.addNameAndType(BASECP,(short)2,(short)1); // "" "()V" // cp item 14 BASECP = Bytecode.addNameAndType(BASECP,(short)4,(short)9); // "eventProcessor" "Lorg/apache/bsf/util/event/EventProcessor;" // cp item 15 BASECP = Bytecode.addFieldRef(BASECP,(short)11,(short)14); // cp item 16 BASECP = Bytecode.addMethodRef(BASECP,(short)11,(short)13); // fixed bytes in middle of class file FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0x21); // access_flags (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)20); // this_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)11); // super_class (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)1); // interface_count (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)19); // interfaces (fixed) FIXEDCLASSBYTES = ByteUtility.addBytes(FIXEDCLASSBYTES,(short)0); // field_count (fixed) // initialization method, constructor INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // access_flags INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)2); // name_index "" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // descriptor_index "()V" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // attribute_count INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)3); // attribute_name_index "Code" INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)17); // attribute_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_stack INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)1); // max_locals INITMETHOD = ByteUtility.addBytes(INITMETHOD,(long)5); // code_length //code INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0x2A); // aload_0 INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB7); // invokespecial INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)16); // method_ref index INITMETHOD = ByteUtility.addBytes(INITMETHOD,(byte)0xB1); // return // exception table INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // exception_table_length INITMETHOD = ByteUtility.addBytes(INITMETHOD,(short)0); // attributes_count } /* methods that take an EventListener Class Type to create an EventAdapterClass */ public static Class makeEventAdapterClass(Class listenerType,boolean writeClassFile) { logger.debug("EventAdapterGenerator"); if( EVENTLISTENER.isAssignableFrom(listenerType) ) { boolean exceptionable = false; boolean nonExceptionable = false; byte constantPool[] = null; short cpBaseIndex; short cpCount = 0; short cpExceptionBaseIndex; short exceptionableCount; short nonExceptionableCount; /* Derive Names */ String listenerTypeName = listenerType.getName(); logger.debug("ListenerTypeName: "+listenerTypeName); String adapterClassName = CLASSPACKAGE+ (listenerTypeName.endsWith("Listener") ? listenerTypeName.substring(0, listenerTypeName.length() - 8) : listenerTypeName).replace('.', '_') + "Adapter"; String finalAdapterClassName = adapterClassName; Class cached = null; int suffixIndex = 0; do { if (null != (cached = ldr.getLoadedClass(finalAdapterClassName))) { logger.debug("cached: "+cached); try { if (!listenerType.isAssignableFrom(cached)) finalAdapterClassName = adapterClassName + "_" + suffixIndex++; else return cached; } catch(VerifyError ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); return cached; } } } while (cached != null); String eventListenerName = listenerTypeName.replace('.', '/'); /* method stuff */ java.lang.reflect.Method lms[] = listenerType.getMethods(); /* ****************************************************************************************** */ // Listener interface // Class name cpCount += 4; // cp item 17 constantPool = Bytecode.addUtf8(constantPool,eventListenerName); // cp item 18 constantPool = Bytecode.addUtf8(constantPool,finalAdapterClassName); // cp item 19 constantPool = Bytecode.addClass(constantPool,(short)17); // cp item 20 constantPool = Bytecode.addClass(constantPool,(short)18); // do we have nonExceptionalble event, exceptionable or both for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); if( 0 < exceptionTypes.length) { exceptionable = true; } else { nonExceptionable = true; } }/* End for*/ /* ****************************************************************************************** */ // optional inclusion of nonexceptional events affects exceptional events indices nonExceptionableCount = 0; if(nonExceptionable) { nonExceptionableCount = 3; cpCount += nonExceptionableCount; // cp item 21 constantPool = Bytecode.addUtf8(constantPool,"processEvent"); // cp item 22 constantPool = Bytecode.addNameAndType(constantPool,(short)21,(short)8); // cp item 23 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)22); } /* ****************************************************************************************** */ // optional inclusion of exceptional events affects CP Items which follow for specific methods exceptionableCount = 0; if(exceptionable) { int classIndex = BASECPCOUNT + cpCount + 1; int nameIndex = BASECPCOUNT + cpCount + 0; int natIndex = BASECPCOUNT + cpCount + 3; exceptionableCount = 5; cpCount += exceptionableCount; // cp item 24 or 21 constantPool = Bytecode.addUtf8(constantPool,"processExceptionableEvent"); // cp item 25 or 22 constantPool = Bytecode.addUtf8(constantPool,"java/lang/Exception"); // cp item 26 or 23 constantPool = Bytecode.addClass(constantPool,(short)classIndex); // cp item 27 or 24 constantPool = Bytecode.addNameAndType(constantPool,(short)nameIndex,(short)8); // cp item 28 or 25 constantPool = Bytecode.addInterfaceMethodRef(constantPool,(short)12,(short)natIndex); } // base index for method cp references cpBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpBaseIndex: " + cpBaseIndex); for (int i = 0 ; i < lms.length ; ++i) { String eventMethodName = lms[i].getName(); String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); cpCount += 3; // cp items for event methods constantPool = Bytecode.addUtf8(constantPool,eventMethodName); constantPool = Bytecode.addUtf8(constantPool,("(L" + eventName + ";)V")); constantPool = Bytecode.addString(constantPool,(short)(BASECPCOUNT+cpCount-3)); }/* End for*/ boolean propertyChangeFlag[] = new boolean[lms.length]; int cpIndexPCE = 0; for (int i = 0 ; i < lms.length ; ++i) { String eventName = lms[i].getParameterTypes()[0].getName().replace('.','/'); // cp items for PropertyChangeEvent special handling if(eventName.equalsIgnoreCase("java/beans/PropertyChangeEvent")) { propertyChangeFlag[i] = true; if( 0 == cpIndexPCE ) { constantPool = Bytecode.addUtf8(constantPool,eventName); constantPool = Bytecode.addUtf8(constantPool,"getPropertyName"); constantPool = Bytecode.addUtf8(constantPool,"()Ljava/lang/String;"); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT + cpCount)); constantPool = Bytecode.addNameAndType(constantPool, (short)(BASECPCOUNT + cpCount + 1), (short)(BASECPCOUNT + cpCount + 2)); constantPool = Bytecode.addMethodRef(constantPool, (short)(BASECPCOUNT + cpCount + 3), (short)(BASECPCOUNT + cpCount + 4)); cpCount += 6; cpIndexPCE = BASECPCOUNT + cpCount - 1; } } else { propertyChangeFlag[i] = false; } }/* End for*/ cpExceptionBaseIndex = (short)(BASECPCOUNT + cpCount); logger.debug("cpExceptionBaseIndex: " + cpExceptionBaseIndex); int excpIndex[][] = new int[lms.length][]; for (int i = 0 ; i < lms.length ; ++i) { Class exceptionTypes[] = lms[i].getExceptionTypes(); excpIndex[i] = new int[exceptionTypes.length]; for ( int j = 0 ; j < exceptionTypes.length ; j++) { constantPool = Bytecode.addUtf8(constantPool,exceptionTypes[j].getName().replace('.', '/')); constantPool = Bytecode.addClass(constantPool,(short)(BASECPCOUNT+cpCount)); excpIndex[i][j] = BASECPCOUNT + cpCount + 1; cpCount += 2; } }/* End for*/ /* end constant pool */ /* ************************************************************************************************ */ // put the Class byte array together /* start */ byte newClass[] = CLASSHEADER; // magic, version (fixed) short count = (short)(BASECPCOUNT + cpCount); newClass = ByteUtility.addBytes(newClass,count); // constant_pool_count (variable) newClass = ByteUtility.addBytes(newClass,BASECP); // constant_pool (fixed) newClass = ByteUtility.addBytes(newClass,constantPool); // constant_pool (variable) newClass = ByteUtility.addBytes(newClass,FIXEDCLASSBYTES); // see FIXEDCLASSBYTES (fixed) newClass = ByteUtility.addBytes(newClass,(short)(lms.length+1)); // method_count (variable) newClass = ByteUtility.addBytes(newClass,INITMETHOD); // constructor (fixed) // methods /* ****************************************************************************************** */ /* loop over listener methods from listenerType */ for (int i = 0 ; i < lms.length ; ++i) { newClass = ByteUtility.addBytes(newClass,(short)1); // access_flags (fixed) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+0)); // name_index (variable) newClass = ByteUtility.addBytes(newClass,(short)(cpBaseIndex+3*i+1)); // descriptor_index (variable) newClass = ByteUtility.addBytes(newClass,(short)1); // attribute_count (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // attribute_name_index code(fixed) // Code Attribute Length int length = 32; if( 0 < excpIndex[i].length ) { length += 5 + 8 * ( 1 + excpIndex[i].length ); } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // attribute_length (variable) // start code attribute newClass = ByteUtility.addBytes(newClass,(short)6); // max_stack (fixed) newClass = ByteUtility.addBytes(newClass,(short)3); // max_locals (fixed) // Code Length length = 20; if(exceptionable && 0 < excpIndex[i].length) { length += 5; } if(propertyChangeFlag[i]) { length += 2; } newClass = ByteUtility.addBytes(newClass,(long)length); // code_length (variable) // start code newClass = ByteUtility.addBytes(newClass,(byte)0x2A); // aload_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB4); // getfield (fixed) newClass = ByteUtility.addBytes(newClass,(short)15); // index (fixed) if(propertyChangeFlag[i]) { // the propertyName is passed as the first parameter newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB6); // invokevirtual (fixed) newClass = ByteUtility.addBytes(newClass,(short)cpIndexPCE); // methodref (variable) } else { // the eventMethodName is passed as the first parameter // Target for method invocation. newClass = ByteUtility.addBytes(newClass,(byte)0x12); // ldc (fixed) newClass = ByteUtility.addBytes(newClass,(byte)(cpBaseIndex+3*i+2)); // index (byte) (variable) } newClass = ByteUtility.addBytes(newClass,(byte)0x04); // iconst_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBD); // anewarray (fixed) newClass = ByteUtility.addBytes(newClass,(short)10); // Class java/lang/Object (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x59); // dup (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2B); // aload_1 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x53); // aastore (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB9); // invokeinterface (fixed) // index to processEvent or processExceptionableEvent method length = 23; // actually an index into cp if(exceptionable && nonExceptionable) { // interface method index if( 0 < lms[i].getExceptionTypes().length ) { length += 5; } } else if(exceptionable) { length += 2; } newClass = ByteUtility.addBytes(newClass,(short)length); // index (process??????...) (variable) newClass = ByteUtility.addBytes(newClass,(byte)0x03); // iconst_0 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x00); // noop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) if(exceptionable && 0 < excpIndex[i].length) { // exception code newClass = ByteUtility.addBytes(newClass,(byte)0x4D); // astore_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x2C); // aload_2 (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xBF); // athrow (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0x57); // pop (fixed) newClass = ByteUtility.addBytes(newClass,(byte)0xB1); // return (fixed) // end code // exception table length = excpIndex[i].length; newClass = ByteUtility.addBytes(newClass,(short)(1+length)); // exception_table_length (variable) for( int j = 0 ; j < length ; j++ ) { // catch exception types and rethrow newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)22); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)20); // handler_pc (fixed) } newClass = ByteUtility.addBytes(newClass,(short)excpIndex[i][j]); // catch_type (variable) } // catch "exception" and trap it newClass = ByteUtility.addBytes(newClass,(short)0); // start_pc (fixed) if(propertyChangeFlag[i]) { newClass = ByteUtility.addBytes(newClass,(short)21); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)25); // handler_pc (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)19); // end_pc (fixed) newClass = ByteUtility.addBytes(newClass,(short)23); // handler_pc (fixed) } if(nonExceptionable) { newClass = ByteUtility.addBytes(newClass,(short)26); } // catch_type (fixed) else // or { newClass = ByteUtility.addBytes(newClass,(short)23); } // catch_type (fixed) } else { newClass = ByteUtility.addBytes(newClass,(short)0); } // exception_table_length (fixed) // attributes on the code attribute (none) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) // end code attribute }/* End for*/ // Class Attributes (none for this) newClass = ByteUtility.addBytes(newClass,(short)0); // attribute_count (fixed) /* done */ logger.debug("adapterName: " + finalAdapterClassName); logger.debug("cpCount: " + count + " = " + BASECPCOUNT + " + " + cpCount); logger.debug("methodCount: " + (lms.length+1)); // output to disk class file /* ****************************************************************************************** */ // now create the class and load it // return the Class. if (writeClassFile) { try { // removed "WRITEDIRECTORY+", as this path is already part of 'finalAdapterClassName' FileOutputStream fos = new FileOutputStream(finalAdapterClassName+".class"); fos.write(newClass); fos.close(); } catch(IOException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { Class ret = ldr.loadClass(finalAdapterClassName); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } try { Class ret = ldr.defineClass(finalAdapterClassName,newClass); logger.debug("EventAdapterGenerator: " + ret.getName() + " dynamically generated"); return ret; } catch(Throwable ex) // rgf, 2012-01-15 { System.err.println(ex.getMessage()); ex.printStackTrace(); } } return null; } }
blob data class, long method t t f data class, long method blob 0 10389 https://github.com/apache/commons-bsf/blob/88b2601a3caecc32aba38f2b3980d646e9a1b698/src/main/java/org/apache/bsf/util/event/generator/EventAdapterGenerator.java/#L46-L606 1 1236 10389
1991 {"response": "YES I found bad smells", "detected bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } }
long method long method, data class t t t  data class   0 12682 https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 1 1991 12682
1470   {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } }
blob long method, data class t t f long method, data class blob 0 11048 https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 1 1470 11048
4211         { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; }
feature envy long method, data class t t f long method, data class feature envy 0 11086 https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 1 4211 11086
218 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class HDFSTextLineReader { private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; private int bufferSize = DEFAULT_BUFFER_SIZE; private FSDataInputStream reader; private byte[] buffer; // the number of bytes of real data in the buffer private int bufferLength = 0; // the current position in the buffer private int bufferPosn = 0; private long currentFilePos = 0L; private static final byte CR = '\r'; private static final byte LF = '\n'; public static final String KEY_BUFFER_SIZE = "io.file.buffer.size"; /** * Create a line reader that reads from the given stream using the * default buffer-size (32k). * * @param in * The input stream * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in) throws IOException { this(in, DEFAULT_BUFFER_SIZE); } /** * Create a line reader that reads from the given stream using the * given buffer-size. * * @param in * The input stream * @param bufferSize * Size of the read buffer * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, int bufferSize) throws IOException { this.reader = in; this.bufferSize = bufferSize; this.buffer = new byte[this.bufferSize]; currentFilePos = in.getPos(); } public HDFSTextLineReader() throws IOException { this.bufferSize = DEFAULT_BUFFER_SIZE; this.buffer = new byte[this.bufferSize]; } /** * Create a line reader that reads from the given stream using the io.file.buffer.size specified in the given Configuration. * * @param in * input stream * @param conf * configuration * @throws IOException */ public HDFSTextLineReader(FSDataInputStream in, Configuration conf) throws IOException { this(in, conf.getInt(KEY_BUFFER_SIZE, DEFAULT_BUFFER_SIZE)); } /** * Read one line from the InputStream into the given Text. A line * can be terminated by one of the following: '\n' (LF) , '\r' (CR), * or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated * line. * * @param str * the object to store the given line (without newline) * @param maxLineLength * the maximum number of bytes to store into str; * the rest of the line is silently discarded. * @param maxBytesToConsume * the maximum number of bytes to consume * in this call. This is only a hint, because if the line cross * this threshold, we allow it to happen. It can overshoot * potentially by as much as one buffer length. * @return the number of bytes read including the (longest) newline * found. * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { /* We're reading data from in, but the head of the stream may be * already buffered in buffer, so we have several cases: * 1. No newline characters are in the buffer, so we need to copy * everything and read another buffer from the stream. * 2. An unambiguously terminated line is in buffer, so we just * copy to str. * 3. Ambiguously terminated line is in buffer, i.e. buffer ends * in CR. In this case we copy everything up to CR to str, but * we also need to see what follows CR: if it's LF, then we * need consume LF as well, so next call to readLine will read * from after that. * We use a flag prevCharCR to signal if previous character was CR * and, if it happens to be at the end of the buffer, delay * consuming it until we have a chance to look at the char that * follows. */ str.clear(); int txtLength = 0; //tracks str.getLength(), as an optimization int newlineLength = 0; //length of terminating newline boolean prevCharCR = false; //true of prev char was CR long bytesConsumed = 0; do { int startPosn = bufferPosn; //starting from where we left off the last time if (bufferPosn >= bufferLength) { startPosn = bufferPosn = 0; if (prevCharCR) ++bytesConsumed; //account for CR from previous read bufferLength = reader.read(buffer); if (bufferLength <= 0) break; // EOF } for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline if (buffer[bufferPosn] == LF) { newlineLength = (prevCharCR) ? 2 : 1; ++bufferPosn; // at next invocation proceed from following byte break; } if (prevCharCR) { //CR + notLF, we are at notLF newlineLength = 1; break; } prevCharCR = (buffer[bufferPosn] == CR); } int readLength = bufferPosn - startPosn; if (prevCharCR && newlineLength == 0) --readLength; //CR at the end of the buffer bytesConsumed += readLength; int appendLength = readLength - newlineLength; if (appendLength > maxLineLength - txtLength) { appendLength = maxLineLength - txtLength; } if (appendLength > 0) { str.append(buffer, startPosn, appendLength); txtLength += appendLength; } } while (newlineLength == 0 && bytesConsumed < maxBytesToConsume); if (bytesConsumed > Integer.MAX_VALUE) throw new IOException("Too many bytes before newline: " + bytesConsumed); currentFilePos = reader.getPos() - bufferLength + bufferPosn; return (int) bytesConsumed; } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @param maxLineLength * the maximum number of bytes to store into str. * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str, int maxLineLength) throws IOException { return readLine(str, maxLineLength, Integer.MAX_VALUE); } /** * Read from the InputStream into the given Text. * * @param str * the object to store the given line * @return the number of bytes read including the newline * @throws IOException * if the underlying stream throws */ public int readLine(Text str) throws IOException { return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE); } public void seek(long desired) throws IOException { if (reader.getPos() <= desired || currentFilePos > desired) { // desired position is ahead of stream or before the current position, seek to position reader.seek(desired); bufferLength = 0; bufferPosn = 0; currentFilePos = desired; } else if (currentFilePos < desired) { // desired position is in the buffer int difference = (int) (desired - currentFilePos); bufferPosn += difference; currentFilePos = desired; } } public FSDataInputStream getReader() { return reader; } public void resetReader(FSDataInputStream reader) throws IOException { this.reader = reader; bufferLength = 0; bufferPosn = 0; currentFilePos = reader.getPos(); } public void close() throws IOException { reader.close(); } }
blob long method, data class t t f long method, data class blob 0 2369 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/HDFSTextLineReader.java/#L27-L234 1 218 2369
2343 { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } }
long method data class, long method t t t data class   0 14182 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 1 2343 14182
1651  { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; }
long method 1 Long Method, 2 Data Class t f t  2. Data Class   0 11579 https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 1 1651 11579
2013   YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code (similar code blocks for different parameters) 3. Data class (the method is only performing data validation, which could be separated into its own class) 4. Feature envy (the use of a different helper class for extracting data) 5. Long parameter list (the method has a large number of parameters) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); }
long method  Long method2 Repetitive code (similar code blocks for different parameters)3 Data class (the method is only performing data validation, which could be separated into its own class)4 Feature envy (the use of a different helper class for extracting data)5 Long parameter list (the method has a large number of parameters) t f t  which could be separated into its own class)4. Feature envy (the use of a different helper class for extracting data)5. Long parameter list (the method has a large number of parameters)   0 12755 https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 2 2013 12755
1549 {"response": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl
blob Blob, Data Class t f t  Data Class   0 11262 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 1 1549 11262
1654  {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; }
long method Long Method, Data Class t f t  Data Class   0 11585 https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 1 1654 11585
4577  {"message": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class ParsableByteArray { public byte[] data; private int position; private int limit; /** Creates a new instance that initially has no backing data. */ public ParsableByteArray() { data = Util.EMPTY_BYTE_ARRAY; } /** * Creates a new instance with {@code limit} bytes and sets the limit. * * @param limit The limit to set. */ public ParsableByteArray(int limit) { this.data = new byte[limit]; this.limit = limit; } /** * Creates a new instance wrapping {@code data}, and sets the limit to {@code data.length}. * * @param data The array to wrap. */ public ParsableByteArray(byte[] data) { this.data = data; limit = data.length; } /** * Creates a new instance that wraps an existing array. * * @param data The data to wrap. * @param limit The limit to set. */ public ParsableByteArray(byte[] data, int limit) { this.data = data; this.limit = limit; } /** Sets the position and limit to zero. */ public void reset() { position = 0; limit = 0; } /** * Resets the position to zero and the limit to the specified value. If the limit exceeds the * capacity, {@code data} is replaced with a new array of sufficient size. * * @param limit The limit to set. */ public void reset(int limit) { reset(capacity() < limit ? new byte[limit] : data, limit); } /** * Updates the instance to wrap {@code data}, and resets the position to zero and the limit to * {@code data.length}. * * @param data The array to wrap. */ public void reset(byte[] data) { reset(data, data.length); } /** * Updates the instance to wrap {@code data}, and resets the position to zero. * * @param data The array to wrap. * @param limit The limit to set. */ public void reset(byte[] data, int limit) { this.data = data; this.limit = limit; position = 0; } /** * Returns the number of bytes yet to be read. */ public int bytesLeft() { return limit - position; } /** * Returns the limit. */ public int limit() { return limit; } /** * Sets the limit. * * @param limit The limit to set. */ public void setLimit(int limit) { Assertions.checkArgument(limit >= 0 && limit <= data.length); this.limit = limit; } /** * Returns the current offset in the array, in bytes. */ public int getPosition() { return position; } /** * Returns the capacity of the array, which may be larger than the limit. */ public int capacity() { return data.length; } /** * Sets the reading offset in the array. * * @param position Byte offset in the array from which to read. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void setPosition(int position) { // It is fine for position to be at the end of the array. Assertions.checkArgument(position >= 0 && position <= limit); this.position = position; } /** * Moves the reading offset by {@code bytes}. * * @param bytes The number of bytes to skip. * @throws IllegalArgumentException Thrown if the new position is neither in nor at the end of the * array. */ public void skipBytes(int bytes) { setPosition(position + bytes); } /** * Reads the next {@code length} bytes into {@code bitArray}, and resets the position of * {@code bitArray} to zero. * * @param bitArray The {@link ParsableBitArray} into which the bytes should be read. * @param length The number of bytes to write. */ public void readBytes(ParsableBitArray bitArray, int length) { readBytes(bitArray.data, 0, length); bitArray.setPosition(0); } /** * Reads the next {@code length} bytes into {@code buffer} at {@code offset}. * * @see System#arraycopy(Object, int, Object, int, int) * @param buffer The array into which the read data should be written. * @param offset The offset in {@code buffer} at which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(byte[] buffer, int offset, int length) { System.arraycopy(data, position, buffer, offset, length); position += length; } /** * Reads the next {@code length} bytes into {@code buffer}. * * @see ByteBuffer#put(byte[], int, int) * @param buffer The {@link ByteBuffer} into which the read data should be written. * @param length The number of bytes to read. */ public void readBytes(ByteBuffer buffer, int length) { buffer.put(data, position, length); position += length; } /** * Peeks at the next byte as an unsigned value. */ public int peekUnsignedByte() { return (data[position] & 0xFF); } /** * Peeks at the next char. */ public char peekChar() { return (char) ((data[position] & 0xFF) << 8 | (data[position + 1] & 0xFF)); } /** * Reads the next byte as an unsigned value. */ public int readUnsignedByte() { return (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readUnsignedShort() { return (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next two bytes as an unsigned value. */ public int readLittleEndianUnsignedShort() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8; } /** * Reads the next two bytes as a signed value. */ public short readShort() { return (short) ((data[position++] & 0xFF) << 8 | (data[position++] & 0xFF)); } /** * Reads the next two bytes as a signed value. */ public short readLittleEndianShort() { return (short) ((data[position++] & 0xFF) | (data[position++] & 0xFF) << 8); } /** * Reads the next three bytes as an unsigned value. */ public int readUnsignedInt24() { return (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value. */ public int readInt24() { return ((data[position++] & 0xFF) << 24) >> 8 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next three bytes as a signed value in little endian order. */ public int readLittleEndianInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next three bytes as an unsigned value in little endian order. */ public int readLittleEndianUnsignedInt24() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16; } /** * Reads the next four bytes as an unsigned value. */ public long readUnsignedInt() { return (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next four bytes as an unsigned value in little endian order. */ public long readLittleEndianUnsignedInt() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24; } /** * Reads the next four bytes as a signed value */ public int readInt() { return (data[position++] & 0xFF) << 24 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); } /** * Reads the next four bytes as a signed value in little endian order. */ public int readLittleEndianInt() { return (data[position++] & 0xFF) | (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF) << 16 | (data[position++] & 0xFF) << 24; } /** * Reads the next eight bytes as a signed value. */ public long readLong() { return (data[position++] & 0xFFL) << 56 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL); } /** * Reads the next eight bytes as a signed value in little endian order. */ public long readLittleEndianLong() { return (data[position++] & 0xFFL) | (data[position++] & 0xFFL) << 8 | (data[position++] & 0xFFL) << 16 | (data[position++] & 0xFFL) << 24 | (data[position++] & 0xFFL) << 32 | (data[position++] & 0xFFL) << 40 | (data[position++] & 0xFFL) << 48 | (data[position++] & 0xFFL) << 56; } /** * Reads the next four bytes, returning the integer portion of the fixed point 16.16 integer. */ public int readUnsignedFixedPoint1616() { int result = (data[position++] & 0xFF) << 8 | (data[position++] & 0xFF); position += 2; // Skip the non-integer portion. return result; } /** * Reads a Synchsafe integer. * * Synchsafe integers keep the highest bit of every byte zeroed. A 32 bit synchsafe integer can * store 28 bits of information. * * @return The parsed value. */ public int readSynchSafeInt() { int b1 = readUnsignedByte(); int b2 = readUnsignedByte(); int b3 = readUnsignedByte(); int b4 = readUnsignedByte(); return (b1 << 21) | (b2 << 14) | (b3 << 7) | b4; } /** * Reads the next four bytes as an unsigned integer into an integer, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readUnsignedIntToInt() { int result = readInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a little endian unsigned integer into an integer, if the top bit * is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public int readLittleEndianUnsignedIntToInt() { int result = readLittleEndianInt(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next eight bytes as an unsigned long into a long, if the top bit is a zero. * * @throws IllegalStateException Thrown if the top bit of the input data is set. */ public long readUnsignedLongToLong() { long result = readLong(); if (result < 0) { throw new IllegalStateException("Top bit not zero: " + result); } return result; } /** * Reads the next four bytes as a 32-bit floating point value. */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Reads the next eight bytes as a 64-bit floating point value. */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Reads the next {@code length} bytes as UTF-8 characters. * * @param length The number of bytes to read. * @return The string encoded by the bytes. */ public String readString(int length) { return readString(length, Charset.forName(C.UTF8_NAME)); } /** * Reads the next {@code length} bytes as characters in the specified {@link Charset}. * * @param length The number of bytes to read. * @param charset The character set of the encoded characters. * @return The string encoded by the bytes in the specified character set. */ public String readString(int length, Charset charset) { String result = new String(data, position, length, charset); position += length; return result; } /** * Reads the next {@code length} bytes as UTF-8 characters. A terminating NUL byte is discarded, * if present. * * @param length The number of bytes to read. * @return The string, not including any terminating NUL byte. */ public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } /** * Reads up to the next NUL byte (or the limit) as UTF-8 characters. * * @return The string not including any terminating NUL byte, or null if the end of the data has * already been reached. */ public @Nullable String readNullTerminatedString() { if (bytesLeft() == 0) { return null; } int stringLimit = position; while (stringLimit < limit && data[stringLimit] != 0) { stringLimit++; } String string = Util.fromUtf8Bytes(data, position, stringLimit - position); position = stringLimit; if (position < limit) { position++; } return string; } /** * Reads a line of text. * * A line is considered to be terminated by any one of a carriage return ('\r'), a line feed * ('\n'), or a carriage return followed immediately by a line feed ('\r\n'). The system's default * charset (UTF-8) is used. This method discards leading UTF-8 byte order marks, if present. * * @return The line not including any line-termination characters, or null if the end of the data * has already been reached. */ public @Nullable String readLine() { if (bytesLeft() == 0) { return null; } int lineLimit = position; while (lineLimit < limit && !Util.isLinebreak(data[lineLimit])) { lineLimit++; } if (lineLimit - position >= 3 && data[position] == (byte) 0xEF && data[position + 1] == (byte) 0xBB && data[position + 2] == (byte) 0xBF) { // There's a UTF-8 byte order mark at the start of the line. Discard it. position += 3; } String line = Util.fromUtf8Bytes(data, position, lineLimit - position); position = lineLimit; if (position == limit) { return line; } if (data[position] == '\r') { position++; if (position == limit) { return line; } } if (data[position] == '\n') { position++; } return line; } /** * Reads a long value encoded by UTF-8 encoding * * @throws NumberFormatException if there is a problem with decoding * @return Decoded long value */ public long readUtf8EncodedLong() { int length = 0; long value = data[position]; // find the high most 0 bit for (int j = 7; j >= 0; j--) { if ((value & (1 << j)) == 0) { if (j < 6) { value &= (1 << j) - 1; length = 7 - j; } else if (j == 7) { length = 1; } break; } } if (length == 0) { throw new NumberFormatException("Invalid UTF-8 sequence first byte: " + value); } for (int i = 1; i < length; i++) { int x = data[position + i]; if ((x & 0xC0) != 0x80) { // if the high most 0 bit not 7th throw new NumberFormatException("Invalid UTF-8 sequence continuation byte: " + value); } value = (value << 6) | (x & 0x3F); } position += length; return value; } }
blob data class, long method t t f data class, long method blob 0 12170 https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L27-L584 1 4577 12170
449      { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); }
long method 1. long method, 2. data class t t t  2. data class   0 4369 https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 1 449 4369
1697       { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } }
blob Blob, Data Class, Long Method t f t  Data Class, Long Method   0 11729 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 1 1697 11729
1190    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); }
long method long method, data class t t t  data class   0 10253 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 1 1190 10253
804  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } }
long method long method, data class t t t  data class   0 7620 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 1 804 7620
2119 {"response": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class", "Feature Envy", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } }
blob blob, data class, feature envy, long method t t t  data class, feature envy, long method   0 13201 https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 1 2119 13201
887 { "message": "YES I found bad smells", "detected_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TCPSocketChannel { private AsynchronousSocketChannel channel; private String address; private int port; private String logname; /** * Create a TCPSocketChannel that is blocking but times out connects and writes. * @param address The address to connect to. * @param port The port to connect to. 0 value means don't open. * @param logname A name to use for logging. */ public TCPSocketChannel(String address, int port, String logname) { this.address = address; this.port = port; this.logname = logname; try { connectWithTimeout(); } catch (IOException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (ExecutionException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (InterruptedException e) { Log(Level.SEVERE, "Failed to connectWithTimeout AsynchronousSocketChannel: " + e); } catch (TimeoutException e) { Log(Level.SEVERE, "AsynchronousSocketChannel connectWithTimeout timed out: " + e); } } public int getPort() { return port; } public String getAddress() { return address; } public boolean isValid() { return channel != null; } public boolean isOpen() { return channel.isOpen(); } private void Log(Level level, String message) { TCPUtils.Log(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void SysLog(Level level, String message) { TCPUtils.SysLog(level, "<-" + this.logname + "(" + this.address + ":" + this.port + ") " + message); } private void connectWithTimeout() throws IOException, ExecutionException, InterruptedException, TimeoutException { if (port == 0) return; InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); Log(Level.INFO, "Attempting to open SocketChannel with InetSocketAddress: " + inetSocketAddress); this.channel = AsynchronousSocketChannel.open(); Future connected = this.channel.connect(inetSocketAddress); connected.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); } public void close() { Log(Level.INFO, "Attempting to close channel."); if (this.channel != null) { try { this.channel.close(); } catch (IOException e) { SysLog(Level.SEVERE, "Failed to close channel: " + e); } } } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @return true if message was successfully sent */ public boolean sendTCPString(String message) { return sendTCPString(message, 0); } /** * Send string over TCP to the specified address via the specified port, including a header. * * @param message string to be sent over TCP * @param retries number of times to retry in event of failure * @return true if message was successfully sent */ public boolean sendTCPString(String message, int retries) { Log(Level.FINE, "About to send: " + message); byte[] bytes = message.getBytes(); return sendTCPBytes(bytes, retries); } /** * Send byte buffer over TCP, including a length header. * * @param buffer the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] buffer) { return sendTCPBytes(buffer, 0); } /** * Send byte buffer over TCP, including a length header. * * @param bytes the bytes to send * @param retries number of times to retry in event of failure * @return true if the message was sent successfully */ public boolean sendTCPBytes(byte[] bytes, int retries) { try { ByteBuffer header = createHeader(bytes.length); safeWrite(header); ByteBuffer buffer = ByteBuffer.wrap(bytes); safeWrite(buffer); } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e); try { channel.close(); } catch (IOException ioe) { } if (retries > 0) { try { connectWithTimeout(); } catch (Exception connectException) { SysLog(Level.SEVERE, "Failed to reconnect: " + connectException); return false; } return sendTCPBytes(bytes, retries - 1); } return false; } return true; } /** * Send byte buffer over TCP, including a length header. * * @param srcbuffers the bytes to send * @return true if the message was sent successfully */ public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length) { boolean success = false; try { ByteBuffer header = createHeader(length); ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length]; buffers[0] = header; for (int i = 0; i < srcbuffers.length; i++) buffers[i + 1] = srcbuffers[i]; if (TCPUtils.isLogging()) { long t1 = System.nanoTime(); long bytesWritten = write(buffers); long t2 = System.nanoTime(); double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1)); Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s"); } else { write(buffers); } success = true; } catch (Exception e) { SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e); try { channel.close(); } catch (IOException ioe) {} } return success; } private ByteBuffer createHeader(int length) { ByteBuffer header = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(length); header.flip(); return header; } private void safeWrite(ByteBuffer buffer) throws InterruptedException, TimeoutException, ExecutionException, IOException { while (buffer.remaining() > 0) { Future future = this.channel.write(buffer); int bytesWritten = future.get(TCPUtils.DEFAULT_SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (bytesWritten == 0) { throw new IOException("async write failed to send any bytes."); } } } private long write(ByteBuffer[] buffers) throws InterruptedException, TimeoutException, ExecutionException, IOException { long bytesWritten = 0; for (ByteBuffer b : buffers) { bytesWritten += b.remaining(); safeWrite(b); } return bytesWritten; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 8072 https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/Utils/TCPSocketChannel.java/#L15-L228 1 887 8072
1804    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JodaDateValidator { public enum PostgresDateTimeConstant { // patterns for replacing POSTGRES_FULL_NAME_OF_DAY(true, "day"), POSTGRES_DAY_OF_YEAR(false, "ddd"), POSTGRES_DAY_OF_MONTH(false, "dd"), POSTGRES_DAY_OF_WEEK(false, "d"), POSTGRES_NAME_OF_MONTH(true, "month"), POSTGRES_ABR_NAME_OF_MONTH(true, "mon"), POSTGRES_YEAR(false, "y"), POSTGRES_ISO_4YEAR(false, "iyyy"), POSTGRES_ISO_3YEAR(false, "iyy"), POSTGRES_ISO_2YEAR(false, "iy"), POSTGRES_ISO_1YEAR(false, "i"), POSTGRES_FULL_ERA_NAME(false, "ee"), POSTGRES_NAME_OF_DAY(true, "dy"), POSTGRES_HOUR_12_NAME(false, "hh"), POSTGRES_HOUR_12_OTHER_NAME(false, "hh12"), POSTGRES_HOUR_24_NAME(false, "hh24"), POSTGRES_MINUTE_OF_HOUR_NAME(false, "mi"), POSTGRES_SECOND_OF_MINUTE_NAME(false, "ss"), POSTGRES_MILLISECOND_OF_MINUTE_NAME(false, "ms"), POSTGRES_WEEK_OF_YEAR(false, "ww"), POSTGRES_ISO_WEEK_OF_YEAR(false, "iw"), POSTGRES_MONTH(false, "mm"), POSTGRES_HALFDAY_AM(false, "am"), POSTGRES_HALFDAY_PM(false, "pm"), // pattern modifiers for deleting PREFIX_FM(false, "fm"), PREFIX_FX(false, "fx"), PREFIX_TM(false, "tm"); private final boolean hasCamelCasing; private final String name; PostgresDateTimeConstant(boolean hasCamelCasing, String name) { this.hasCamelCasing = hasCamelCasing; this.name = name; } public boolean hasCamelCasing() { return hasCamelCasing; } public String getName() { return name; } } private static final Map postgresToJodaMap = Maps.newTreeMap(new LengthDescComparator()); public static final String POSTGRES_ESCAPE_CHARACTER = "\""; // jodaTime patterns public static final String JODA_FULL_NAME_OF_DAY = "EEEE"; public static final String JODA_DAY_OF_YEAR = "D"; public static final String JODA_DAY_OF_MONTH = "d"; public static final String JODA_DAY_OF_WEEK = "e"; public static final String JODA_NAME_OF_MONTH = "MMMM"; public static final String JODA_ABR_NAME_OF_MONTH = "MMM"; public static final String JODA_YEAR = "y"; public static final String JODA_ISO_4YEAR = "xxxx"; public static final String JODA_ISO_3YEAR = "xxx"; public static final String JODA_ISO_2YEAR = "xx"; public static final String JODA_ISO_1YEAR = "x"; public static final String JODA_FULL_ERA_NAME = "G"; public static final String JODA_NAME_OF_DAY = "E"; public static final String JODA_HOUR_12_NAME = "h"; public static final String JODA_HOUR_24_NAME = "H"; public static final String JODA_MINUTE_OF_HOUR_NAME = "m"; public static final String JODA_SECOND_OF_MINUTE_NAME = "ss"; public static final String JODA_MILLISECOND_OF_MINUTE_NAME = "SSS"; public static final String JODA_WEEK_OF_YEAR = "w"; public static final String JODA_MONTH = "MM"; public static final String JODA_HALFDAY = "aa"; public static final String JODA_ESCAPE_CHARACTER = "'"; public static final String EMPTY_STRING = ""; static { postgresToJodaMap.put(POSTGRES_FULL_NAME_OF_DAY, JODA_FULL_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_DAY_OF_YEAR, JODA_DAY_OF_YEAR); postgresToJodaMap.put(POSTGRES_DAY_OF_MONTH, JODA_DAY_OF_MONTH); postgresToJodaMap.put(POSTGRES_DAY_OF_WEEK, JODA_DAY_OF_WEEK); postgresToJodaMap.put(POSTGRES_NAME_OF_MONTH, JODA_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_ABR_NAME_OF_MONTH, JODA_ABR_NAME_OF_MONTH); postgresToJodaMap.put(POSTGRES_FULL_ERA_NAME, JODA_FULL_ERA_NAME); postgresToJodaMap.put(POSTGRES_NAME_OF_DAY, JODA_NAME_OF_DAY); postgresToJodaMap.put(POSTGRES_HOUR_12_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_12_OTHER_NAME, JODA_HOUR_12_NAME); postgresToJodaMap.put(POSTGRES_HOUR_24_NAME, JODA_HOUR_24_NAME); postgresToJodaMap.put(POSTGRES_MINUTE_OF_HOUR_NAME, JODA_MINUTE_OF_HOUR_NAME); postgresToJodaMap.put(POSTGRES_SECOND_OF_MINUTE_NAME, JODA_SECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_MILLISECOND_OF_MINUTE_NAME, JODA_MILLISECOND_OF_MINUTE_NAME); postgresToJodaMap.put(POSTGRES_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_MONTH, JODA_MONTH); postgresToJodaMap.put(POSTGRES_HALFDAY_AM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_HALFDAY_PM, JODA_HALFDAY); postgresToJodaMap.put(POSTGRES_ISO_WEEK_OF_YEAR, JODA_WEEK_OF_YEAR); postgresToJodaMap.put(POSTGRES_YEAR, JODA_YEAR); postgresToJodaMap.put(POSTGRES_ISO_1YEAR, JODA_ISO_1YEAR); postgresToJodaMap.put(POSTGRES_ISO_2YEAR, JODA_ISO_2YEAR); postgresToJodaMap.put(POSTGRES_ISO_3YEAR, JODA_ISO_3YEAR); postgresToJodaMap.put(POSTGRES_ISO_4YEAR, JODA_ISO_4YEAR); postgresToJodaMap.put(PREFIX_FM, EMPTY_STRING); postgresToJodaMap.put(PREFIX_FX, EMPTY_STRING); postgresToJodaMap.put(PREFIX_TM, EMPTY_STRING); } /** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format */ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder(pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); } /** * Length decreasing comparator. * Compares PostgresDateTimeConstant names by length, if they have the same length, compares them lexicographically. */ private static class LengthDescComparator implements Comparator { public int compare(PostgresDateTimeConstant o1, PostgresDateTimeConstant o2) { int result = o2.getName().length() - o1.getName().length(); if (result == 0) { return o1.getName().compareTo(o2.getName()); } return result; } } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 12026 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/logical/src/main/java/org/apache/drill/common/expression/fn/JodaDateValidator.java/#L54-L256 1 1804 12026
2603  { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Data class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 15024 https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 1 2603 15024
1584 {"message": "YES, I found bad smells", "the bad smells are": ["1. Long Method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TraversalFieldAccessorFactory implements FieldAccessorFactory { @Override public boolean accept(final Neo4JPersistentProperty f) { final GraphTraversal graphEntityTraversal = f.getAnnotation(GraphTraversal.class); return graphEntityTraversal != null && graphEntityTraversal.traversalBuilder() != FieldTraversalDescriptionBuilder.class && f.getType().equals(Iterable.class); } @Override public FieldAccessor forField(final Neo4JPersistentProperty property) { return new TraversalFieldAccessor(property); } /** * @author Michael Hunger * @since 12.09.2010 */ public static class TraversalFieldAccessor implements FieldAccessor { protected final Neo4JPersistentProperty property; private final FieldTraversalDescriptionBuilder fieldTraversalDescriptionBuilder; private Class target; protected String[] params; public TraversalFieldAccessor(final Neo4JPersistentProperty property) { this.property = property; final GraphTraversal graphEntityTraversal = property.getAnnotation(GraphTraversal.class); this.target = resolveTarget(graphEntityTraversal,property); this.params = graphEntityTraversal.params(); this.fieldTraversalDescriptionBuilder = createTraversalDescription(graphEntityTraversal); } private Class resolveTarget(GraphTraversal graphTraversal, Neo4JPersistentProperty property) { if (!graphTraversal.elementClass().equals(NodeBacked.class)) return graphTraversal.elementClass(); final Class result = property.getTypeInformation().getActualType().getType(); Class[] allowedTypes={NodeBacked.class,RelationshipBacked.class,Node.class,Relationship.class, Path.class}; if (!checkTypes(result,allowedTypes)) throw new IllegalArgumentException("The target result type "+result+" of the traversal is no subclass of the allowed types: "+property+" "+allowedTypes); return result; } private boolean checkTypes(Class target, Class...allowedTypes) { for (Class type : allowedTypes) { if (type.isAssignableFrom(target)) return true; } return false; } @Override public boolean isWriteable(NodeBacked nodeBacked) { return false; } @Override public Object setValue(final NodeBacked nodeBacked, final Object newVal) { throw new InvalidDataAccessApiUsageException("Cannot set readonly traversal description field " + property); } @Override public Object getValue(final NodeBacked nodeBacked) { final TraversalDescription traversalDescription = fieldTraversalDescriptionBuilder.build(nodeBacked, property,params); return doReturn(nodeBacked.findAllByTraversal(target, traversalDescription)); } private FieldTraversalDescriptionBuilder createTraversalDescription(final GraphTraversal graphEntityTraversal) { try { final Class traversalDescriptionClass = graphEntityTraversal.traversalBuilder(); final Constructor constructor = traversalDescriptionClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating TraversalDescription from " + property,e); } } @Override public Object getDefaultImplementation() { return null; } } }
blob 1 Long Method, 2 Data Class t f f 1. Long Method, 2. Data Class blob 0 11366 https://github.com/spring-projects/spring-data-graph/blob/0210210ce436eb83bf200f5d5f9a63a440c5b27a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/fieldaccess/TraversalFieldAccessorFactory.java/#L36-L119 1 1584 11366
1618 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; }
feature envy Long Method, Data Class t f f Long Method, Data Class feature envy 0 11476 https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 1 1618 11476
1418      { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 10924 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 1 1418 10924
1361     { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; }
feature envy long method, data class t t f long method, data class feature envy 0 10778 https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 1 1361 10778
1256 {"response": "YES I found bad smells", "detected_bad_smells": ["2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } }
blob 2. data class t t f 2. data class blob 0 10494 https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 1 1256 10494
1573 {"message":"YES I found bad smells","the bad smells are":["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } }
blob data class t t f data class blob 0 11342 https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 1 1573 11342
750 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@AutoValue public abstract class UPlaceholderExpression extends UExpression { static UPlaceholderExpression create( PlaceholderMethod placeholder, Iterable arguments) { ImmutableList placeholderParams = placeholder.parameters().asList(); ImmutableList argumentsList = ImmutableList.copyOf(arguments); ImmutableMap.Builder builder = ImmutableMap.builder(); for (int i = 0; i < placeholderParams.size(); i++) { builder.put(placeholderParams.get(i), argumentsList.get(i)); } return new AutoValue_UPlaceholderExpression(placeholder, builder.build()); } abstract PlaceholderMethod placeholder(); abstract ImmutableMap arguments(); public static final class PlaceholderParamIdent extends JCIdent { final UVariableDecl param; PlaceholderParamIdent(UVariableDecl param, Context context) { super(Names.instance(context).fromString(param.getName().contents()), null); this.param = checkNotNull(param); } } static class UncheckedCouldNotResolveImportException extends RuntimeException { UncheckedCouldNotResolveImportException(CouldNotResolveImportException e) { super(e); } @Override public synchronized CouldNotResolveImportException getCause() { return (CouldNotResolveImportException) super.getCause(); } } static TreeCopier copier( final Map arguments, Inliner inliner) { return new TreeCopier(inliner.maker()) { @Override public T copy(T tree, Inliner inliner) { if (tree == null) { return null; } T result = super.copy(tree, inliner); if (result.toString().equals(tree.toString())) { return tree; } else { return result; } } @Override public JCTree visitIdentifier(IdentifierTree node, Inliner inliner) { if (node instanceof PlaceholderParamIdent) { try { return arguments.get(((PlaceholderParamIdent) node).param).inline(inliner); } catch (CouldNotResolveImportException e) { throw new UncheckedCouldNotResolveImportException(e); } } else { return super.visitIdentifier(node, inliner); } } }; } @Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { /* * Copy the original source bound to the placeholder, except anywhere we matched a placeholder * parameter, replace that with the corresponding expression in this invocation. */ try { return copier(arguments(), inliner) .copy(inliner.getBinding(placeholder().exprKey()), inliner); } catch (UncheckedCouldNotResolveImportException e) { throw e.getCause(); } } @Override public Kind getKind() { return Kind.OTHER; } @Override public R accept(TreeVisitor visitor, D data) { return visitor.visitOther(this, data); } public boolean reverify(Unifier unifier) { return MoreObjects.firstNonNull( new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()) .scan(unifier.getBinding(placeholder().exprKey()), unifier), true); } @Override protected Choice defaultAction(Tree node, Unifier unifier) { // for now we only match JCExpressions if (placeholder().returnType().equals(UPrimitiveType.VOID) || !(node instanceof JCExpression)) { return Choice.none(); } final JCExpression expr = (JCExpression) node; PlaceholderVerificationVisitor verification = new PlaceholderVerificationVisitor( Collections2.transform( placeholder().requiredParameters(), Functions.forMap(arguments())), arguments().values()); if (!verification.scan(node, unifier) || !verification.allRequiredMatched()) { return Choice.none(); } /* * We copy the tree with a TreeCopier, replacing matches for the parameters with * PlaceholderParamIdents, and updating unifierHolder as we unify things, including forbidding * references to local variables, etc. */ Choice> states = PlaceholderUnificationVisitor.create(TreeMaker.instance(unifier.getContext()), arguments()) .unifyExpression( expr, PlaceholderUnificationVisitor.State.create( List.nil(), unifier, null)); return states.thenOption( (PlaceholderUnificationVisitor.State state) -> { if (ImmutableSet.copyOf(state.seenParameters()) .containsAll(placeholder().requiredParameters())) { Unifier resultUnifier = state.unifier(); JCExpression prevBinding = resultUnifier.getBinding(placeholder().exprKey()); if (prevBinding != null) { return prevBinding.toString().equals(state.result().toString()) ? Optional.of(resultUnifier) : Optional.absent(); } JCExpression result = state.result(); if (!placeholder() .matcher() .matches(result, UMatches.makeVisitorState(expr, resultUnifier))) { return Optional.absent(); } result.type = expr.type; resultUnifier.putBinding(placeholder().exprKey(), result); return Optional.of(resultUnifier); } else { return Optional.absent(); } }); } }
blob long method, data class t t f long method, data class blob 0 7028 https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java/#L45-L201 1 750 7028
223 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TemporalIntervalStartDatetimeAccessor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; private static final FunctionIdentifier FID = BuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_START_DATETIME; public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new TemporalIntervalStartDatetimeAccessor(); } }; @Override public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IScalarEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IScalarEvaluator createScalarEvaluator(IHyracksTaskContext ctx) throws HyracksDataException { return new IScalarEvaluator() { private final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage(); private final DataOutput out = resultStorage.getDataOutput(); private final IPointable argPtr = new VoidPointable(); private final IScalarEvaluator eval = args[0].createScalarEvaluator(ctx); // possible output @SuppressWarnings("unchecked") private final ISerializerDeserializer datetimeSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADATETIME); private final AMutableDateTime aDateTime = new AMutableDateTime(0); @Override public void evaluate(IFrameTupleReference tuple, IPointable result) throws HyracksDataException { eval.evaluate(tuple, argPtr); byte[] bytes = argPtr.getByteArray(); int startOffset = argPtr.getStartOffset(); resultStorage.reset(); try { if (bytes[startOffset] == ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG) { byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes, startOffset + 1); long startTime = AIntervalSerializerDeserializer.getIntervalStart(bytes, startOffset + 1); if (timeType == ATypeTag.SERIALIZED_DATETIME_TYPE_TAG) { aDateTime.setValue(startTime); datetimeSerde.serialize(aDateTime, out); } else { throw new InvalidDataFormatException(sourceLoc, getIdentifier(), ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } else { throw new TypeMismatchException(sourceLoc, getIdentifier(), 0, bytes[startOffset], ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG); } } catch (IOException e) { throw HyracksDataException.create(e); } result.set(resultStorage); } }; } }; } /* (non-Javadoc) * @see org.apache.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } }
blob long method, data class t t f long method, data class blob 0 2416 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/accessors/TemporalIntervalStartDatetimeAccessor.java/#L47-L119 1 223 2416
555 {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } }
blob data class, long method t t f data class, long method blob 0 5607 https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 1 555 5607
896 {"response": "YES, I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Value @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Argument { public static Argument SKIP_TESTS = Argument.arg("skipTests"); @NonNull String name; @NonNull Optional> value; private Argument(String name, ArgumentValue value) { this(name, Optional.of(value)); } static Argument of(String name) { return new Argument(name, Optional.empty()); } /** * Enables the given comma-separated profiles for the {@link CommandLine}. * * @param name must not be {@literal null} or empty. * @return */ public static Argument profile(String name, String... others) { Assert.hasText(name, "Profiles must not be null or empty!"); Assert.notNull(others, "Other profiles must not be null!"); String profiles = Stream.concat(Stream.of(name), Arrays.stream(others)).collect(Collectors.joining(",")); return Argument.of("-P".concat(profiles)); } public static Argument arg(String name) { return Argument.of("-D".concat(name)); } public static Argument debug() { return Argument.of("-X"); } public Argument withValue(Object value) { return new Argument(name, ArgumentValue.of(value)); } public Argument withQuotedValue(Object value) { return new Argument(name, ArgumentValue.of(value, it -> String.format("\"%s\"", it.toString()))); } public Argument withValue(Masked masked) { return new Argument(name, ArgumentValue.of(masked)); } public String toCommandLineArgument() { return toNameValuePair(value.map(ArgumentValue::toCommandLine)); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return toNameValuePair(value.map(Object::toString)); } private String toNameValuePair(Optional source) { return source// .map(it -> String.format("%s=%s", name, it))// .orElse(name); } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class ArgumentValue { private final @NonNull T value; private final @NonNull Optional> preparer; private final @NonNull Optional> toString; public static ArgumentValue of(T value) { return new ArgumentValue<>(value, Optional.empty(), Optional.empty()); } public static ArgumentValue of(T value, Function preparer) { return new ArgumentValue<>(value, Optional.of(preparer), Optional.empty()); } /** * Returns an {@link ArgumentValue} for the given {@link Masked} value. * * @param masked must not be {@literal null}. * @return */ public static ArgumentValue of(T masked) { return new ArgumentValue<>(masked, Optional.empty(), Optional.of(it -> it.masked())); } /** * Returns the {@link String} variant of the argument value. * * @return */ public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return toString.map(it -> it.apply(value)).orElseGet(() -> toCommandLine()); } } }
blob data class, long method t t f data class, long method blob 0 8137 https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L142-L257 1 896 8137
207    { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 2307 https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 1 207 2307
56   { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MapImageLayerTablesSample extends Application { private MapView mapView; private GraphicsOverlay graphicsOverlay; private ServiceFeatureTable commentsTable; private ListView commentsListView; /** * Starting point of this application. * * @param args arguments to this application. */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { // create a stack pane and application scene StackPane stackPane = new StackPane(); Scene scene = new Scene(stackPane); scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); // size the stage and add a title stage.setTitle("Map Image Layer Tables Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(scene); stage.show(); // create a map with a basemap ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); // create and add a map image layer to the map // the map image layer contains a feature table with related spatial and non-spatial comment features ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer"); map.getOperationalLayers().add(imageLayer); // create a map view and set the map to it mapView = new MapView(); mapView.setMap(map); // create a graphics overlay to show the related spatial features in graphicsOverlay = new GraphicsOverlay(); mapView.getGraphicsOverlays().add(graphicsOverlay); // show the related graphics as cyan circles SimpleRenderer renderer = new SimpleRenderer(); renderer.setSymbol(new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF00FFFF, 14)); graphicsOverlay.setRenderer(renderer); // create a list view to show the non-spatial comment features commentsListView = new ListView<>(); commentsListView.setMaxSize(200.0, 150.0); // show the comments attribute of the feature in the list commentsListView.setCellFactory(listView -> new ListCell() { @Override protected void updateItem(Feature item, boolean empty) { super.updateItem(item, empty); if (item != null) { ArcGISFeature feature = (ArcGISFeature) item; setText((String) feature.getAttributes().get("comments")); } } }); // when a comment is selected, query its related spatial features and show the first result on the map commentsListView.getSelectionModel().selectedItemProperty().addListener(observable -> showRelatedRequests()); // when the layer is loaded, get the comment features imageLayer.addDoneLoadingListener(() -> { if (imageLayer.getLoadStatus() == LoadStatus.LOADED) { // zoom to the layer's extent mapView.setViewpoint(new Viewpoint(imageLayer.getFullExtent())); // get the comments feature table commentsTable = imageLayer.getTables().get(0); // create query parameters to get features that have non-empty comments QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause("requestid <> '' AND comments <> ''"); // query the comments table for features ListenableFuture featureQuery = commentsTable.queryFeaturesAsync(queryParameters); featureQuery.addDoneListener(() -> { try { // add the returned features to the list view FeatureQueryResult results = featureQuery.get(); for (Feature f : results) { commentsListView.getItems().addAll(f); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Error querying comment features"); } }); } else { new Alert(Alert.AlertType.ERROR, imageLayer.getLoadError().getMessage()).show(); } }); // add the mapview and controls to the stack pane stackPane.getChildren().addAll(mapView, commentsListView); StackPane.setAlignment(commentsListView, Pos.TOP_LEFT); StackPane.setMargin(commentsListView, new Insets(10, 0, 0, 10)); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } /** * Queries for spatial features related to the selected comment in the list view and shows the first result on the * map as a graphic. */ private void showRelatedRequests() { // clear any previous results graphicsOverlay.getGraphics().clear(); // get the selected comment feature from the list view Feature selectedCommentFeature = commentsListView.getSelectionModel().getSelectedItem(); if (selectedCommentFeature != null) { // get the relationships info between layers in the table ArcGISFeature feature = (ArcGISFeature) selectedCommentFeature; List relationshipInfos = commentsTable.getLayerInfo().getRelationshipInfos(); if (!relationshipInfos.isEmpty()) { // use the first relationship for the related query parameters RelationshipInfo commentsRelationshipInfo = relationshipInfos.get(0); RelatedQueryParameters relatedQueryParameters = new RelatedQueryParameters(commentsRelationshipInfo); relatedQueryParameters.setReturnGeometry(true); // query the table for related features using the parameters ListenableFuture> relatedFeaturesRequest = commentsTable .queryRelatedFeaturesAsync(feature, relatedQueryParameters); relatedFeaturesRequest.addDoneListener(() -> { try { // loop through the returned related features List results = relatedFeaturesRequest.get(); if (!results.isEmpty()) { RelatedFeatureQueryResult relatedResult = results.get(0); if (relatedResult.iterator().hasNext()) { // get the first related feature ArcGISFeature relatedFeature = (ArcGISFeature) relatedResult.iterator().next(); // load the feature and get its geometry to show as a graphic on the map relatedFeature.loadAsync(); relatedFeature.addDoneLoadingListener(() -> { if (relatedFeature.getLoadStatus() == LoadStatus.LOADED) { Point point = (Point) relatedFeature.getGeometry(); Graphic graphic = new Graphic(point); graphicsOverlay.getGraphics().add(graphic); // zoom to the graphic mapView.setViewpointCenterAsync(point, 40000); } }); } } else { new Alert(Alert.AlertType.INFORMATION, "No related features found").show(); } } catch (InterruptedException | ExecutionException ex) { new Alert(Alert.AlertType.ERROR, "Failed to query relationships").show(); } }); } } } @Override public void stop() { // releases resources when the application closes if (mapView != null) { mapView.dispose(); } } }
blob long method, data class t t f long method, data class blob 0 976 https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/imagelayers/map_image_layer_tables/MapImageLayerTablesSample.java/#L53-L234 1 56 976
4062 {"message": "YES, I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } }
blob data class, long method t t f data class, long method blob 0 10721 https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 1 4062 10721
1356   YES I found bad smells the bad smells are: Feature envy, Long method, Data class, Duplicate code I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public static class MissedUpdatesFinder extends MissedUpdatesFinderBase { private long ourHighThreshold; // 80th percentile private long ourHighest; // currently just used for logging/debugging purposes private String logPrefix; private long nUpdates; MissedUpdatesFinder(List ourUpdates, String logPrefix, long nUpdates, long ourLowThreshold, long ourHighThreshold) { super(ourUpdates, ourLowThreshold); this.logPrefix = logPrefix; this.ourHighThreshold = ourHighThreshold; this.ourHighest = ourUpdates.get(0); this.nUpdates = nUpdates; } public MissedUpdatesRequest find(List otherVersions, Object updateFrom, Supplier canHandleVersionRanges) { otherVersions.sort(absComparator); if (debug) { log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom); } long otherHigh = percentile(otherVersions, .2f); long otherLow = percentile(otherVersions, .8f); long otherHighest = otherVersions.get(0); if (ourHighThreshold < otherLow) { // Small overlap between version windows and ours is older // This means that we might miss updates if we attempted to use this method. // Since there exists just one replica that is so much newer, we must // fail the sync. log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (ourLowThreshold > otherHigh && ourHighest >= otherHighest) { // Small overlap between windows and ours is newer. // Using this list to sync would result in requesting/replaying results we don't need // and possibly bringing deleted docs back to life. log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); // Because our versions are newer, IndexFingerprint with the remote would not match us. // We return true on our side, but the remote peersync with us should fail. return MissedUpdatesRequest.ALREADY_IN_SYNC; } boolean completeList = otherVersions.size() < nUpdates; MissedUpdatesRequest updatesRequest; if (canHandleVersionRanges.get()) { updatesRequest = handleVersionsWithRanges(otherVersions, completeList); } else { updatesRequest = handleIndividualVersions(otherVersions, completeList); } if (updatesRequest.totalRequestedUpdates > nUpdates) { log.info("{} PeerSync will fail because number of missed updates is more than:{}", logPrefix, nUpdates); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (updatesRequest == MissedUpdatesRequest.EMPTY) { log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); } return updatesRequest; } }
blob  Feature envy, Long method, Data class, Duplicate code t f f  Feature envy, Long method, Data class, Duplicate code blob 0 10769 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/PeerSync.java/#L787-L856 2 1356 10769
264 { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } }
blob long method, data class t t f long method, data class blob 0 2866 https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 1 264 2866
1917   { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } }
blob data class t t f data class blob 0 12409 https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 1 1917 12409
1205 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; }
feature envy long method, data class t t f long method, data class feature envy 0 10288 https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 1 1205 10288
126 {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 1575 https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 1 126 1575
232      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; }
long method long method, data class t t t  data class   0 2538 https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 1 232 2538
2022 {"message": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } }
blob long method, data class t t f long method, data class blob 0 12792 https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 1 2022 12792
5764   YES I found bad smells the bad smells are: 1. Data Class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } }
long method  Data Class t f f . Data Class long method 0 14546 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 1 5764 14546
1104      { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FunctionTagsTable extends Composite { private final FunctionEditorInput functionEditorInput; private final KeyValueSetEditingComposite tagsEditingComposite; private final KeyValueSetDataModel tagsDataModel; public FunctionTagsTable(Composite parent, FormToolkit toolkit, FunctionEditorInput functionEditorInput) { super(parent, SWT.NONE); this.functionEditorInput = functionEditorInput; this.setLayout(new GridLayout()); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tagsDataModel = new KeyValueSetDataModel(MAX_LAMBDA_TAGS, new ArrayList()); tagsEditingComposite = new KeyValueSetEditingCompositeBuilder() .addKeyValidator(new StringLengthValidator(1, MAX_LAMBDA_TAG_KEY_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_KEY_LENGTH))) .addValueValidator(new StringLengthValidator(0, MAX_LAMBDA_TAG_VALUE_LENGTH, String.format("This field is too long. Maximum length is %d characters.", MAX_LAMBDA_TAG_VALUE_LENGTH))) .addKeyValidator(new LambdaTagNameValidator()) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onSaveTags(); } }) .build(this, tagsDataModel); Composite buttonComposite = new Composite(this, SWT.NONE); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); buttonComposite.setLayout(new GridLayout(1, false)); refresh(); } public void refresh() { Map tagMap = functionEditorInput.getLambdaClient() .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); tagsDataModel.getPairSet().clear(); for (Entry entry : tagMap.entrySet()) { tagsDataModel.getPairSet().add(new Pair(entry.getKey(), entry.getValue())); } tagsEditingComposite.refresh(); } private void onSaveTags() { try { AWSLambda lambda = functionEditorInput.getLambdaClient(); Map oldTagMap = lambda .listTags(new ListTagsRequest() .withResource(functionEditorInput.getFunctionArn())) .getTags(); List tagKeysToBeRemoved = new ArrayList<>(); for (String key : oldTagMap.keySet()) { if (!tagsDataModel.getPairSet().contains(key)) { tagKeysToBeRemoved.add(key); } } Map tagMap = new HashMap<>(); for (Pair pair : tagsDataModel.getPairSet()) { tagMap.put(pair.getKey(), pair.getValue()); } if (!tagKeysToBeRemoved.isEmpty()) { lambda.untagResource(new UntagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTagKeys(tagKeysToBeRemoved)); } lambda.tagResource(new TagResourceRequest() .withResource(functionEditorInput.getFunctionArn()) .withTags(tagMap)); } catch (AWSLambdaException e) { LambdaPlugin.getDefault().reportException(e.getMessage(), e); } } }
blob data class t t f data class blob 0 9849 https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.lambda/src/com/amazonaws/eclipse/explorer/lambda/FunctionTagsTable.java/#L47-L123 1 1104 9849
1464   { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } }
blob long method, data class t t f long method, data class blob 0 11029 https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 1 1464 11029
529 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class SignatureHashBuilder { @Inject private JvmDeclaredTypeSignatureHashProvider hashProvider; @Inject private AnnotationSignatureRelevanceUtil annotationRelevance; private MessageDigest digest; private StringBuilder builder; public SignatureHashBuilder() { digest = createDigest(); if(digest == null) builder = new StringBuilder(); } protected MessageDigest createDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Error creating message digest", e); return null; } } protected SignatureHashBuilder append(String s) { if(digest != null) try { digest.update(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { LOG.error("Error encoding String", e); } if(builder != null) builder.append(s); return this; } public SignatureHashBuilder appendSignature(JvmDeclaredType type) { if (type.getVisibility() != JvmVisibility.PRIVATE) { appendAnnotationReferences(type); appendVisibility(type.getVisibility()).append(" "); if (type.isAbstract()) append("abstract "); if (type.isStatic()) append("static "); if (type.isFinal()) append("final "); append("class ").append(type.getIdentifier()); if (type instanceof JvmTypeParameterDeclarator) appendTypeParameters((JvmTypeParameterDeclarator) type); append("\n").appendSuperTypeSignatures(type).appendMemberSignatures(type, false); } return this; } protected SignatureHashBuilder appendMemberSignatures(JvmDeclaredType type, boolean innerTypesOnly) { Iterable members = type.getMembers(); if(innerTypesOnly) members = filter(members, JvmDeclaredType.class); for (JvmMember member : members) { if (member.getSimpleName() != null) { appendAnnotationReferences(member); if (member instanceof JvmOperation) appendSignature((JvmOperation) member); else if (member instanceof JvmConstructor) appendSignature((JvmConstructor) member); else if (member instanceof JvmField) appendSignature((JvmField) member); else if (member instanceof JvmDeclaredType) { append(member.getQualifiedName()); appendMemberSignatures((JvmDeclaredType) member, true); } append("\n"); } } return this; } protected void appendAnnotationReferences(JvmAnnotationTarget target) { for(JvmAnnotationReference annotationReference: target.getAnnotations()) { if(annotationRelevance.isRelevant(annotationReference)) append(hashProvider.getHash(annotationReference.getAnnotation())) .append(" "); } } protected SignatureHashBuilder appendSuperTypeSignatures(JvmDeclaredType type) { for(JvmTypeReference superType: type.getSuperTypes()) { append("super "); append(superType.getIdentifier()); append("\n"); } return this; } protected SignatureHashBuilder appendSignature(JvmOperation operation) { appendVisibility(operation.getVisibility()).append(" "); if (operation.isAbstract()) append("abstract "); if (operation.isStatic()) append("static "); if (operation.isFinal()) append("final "); appendType(operation.getReturnType()).appendTypeParameters(operation).append(" ") .append(operation.getSimpleName()).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()); append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendSignature(JvmField field) { appendVisibility(field.getVisibility()).append(" "); if (field.isStatic()) append("static "); if (field.isFinal()) append("final "); return appendType(field.getType()).append(" ").append(field.getSimpleName()); } protected SignatureHashBuilder appendSignature(JvmConstructor operation) { appendVisibility(operation.getVisibility()).appendTypeParameters(operation).append("("); for (JvmFormalParameter p : operation.getParameters()) { appendType(p.getParameterType()).append(" "); } append(") "); for (JvmTypeReference ex : operation.getExceptions()) { appendType(ex).append(" "); } return this; } protected SignatureHashBuilder appendTypeParameters(JvmTypeParameterDeclarator decl) { append("<"); for (JvmTypeParameter tp : decl.getTypeParameters()) { appendTypeParameter(tp).append(","); } append(">"); return this; } protected SignatureHashBuilder appendType(JvmTypeReference ref) { if (ref != null && ref.getIdentifier() != null) { append(ref.getIdentifier()); } else { append("*unresolved*"); } return this; } protected SignatureHashBuilder appendVisibility(JvmVisibility v) { append(v.getLiteral()); return this; } protected SignatureHashBuilder appendTypeParameter(JvmTypeParameter p) { if (p != null && p.getIdentifier() != null) { append(p.getIdentifier()); } else { append("*unresolved*"); } return this; } public String hash() { try { if(digest != null) { byte[] digestBytes = digest.digest(); return new BigInteger(digestBytes).toString(16); } else { return builder.toString(); } } catch (Exception e) { LOG.error("Error hashing JvmDeclaredType signature", e); return ""; } } }
blob data class t t f data class blob 0 5454 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/descriptions/JvmDeclaredTypeSignatureHashProvider.java/#L77-L261 1 529 5454
744 {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CloudCliServiceLaunchConfigurationDelegate extends BootCliLaunchConfigurationDelegate { private static final VersionRange SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE = new VersionRange("1.3.0"); public final static String TYPE_ID = "org.springframework.ide.eclipse.boot.launch.cloud.cli.service"; public final static String ATTR_CLOUD_SERVICE_ID = "local-cloud-service-id"; private final static String PREF_DONT_SHOW_PLATFORM_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.NotSupportedPlatform"; private final static String PREF_DONT_SHOW_JRE_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JRE"; private final static String PREF_DONT_SHOW_JDK_WARNING = "org.springframework.ide.eclipse.boot.launch.cloud.cli.JDK"; private List getCloudCliServiceLifeCycleVmArguments(ILaunchConfiguration configuration, int jmxPort) { List vmArgs = new ArrayList<>(); EnumSet enabled = BootLaunchConfigurationDelegate .getEnabledJmxFeatures(configuration); if (!enabled.isEmpty()) { String enableLiveBeanArgs = JmxBeanSupport.jmxBeanVmArgs(jmxPort, enabled); vmArgs.addAll(Arrays.asList(enableLiveBeanArgs.split("\n"))); } return vmArgs; } protected String[] getProgramArgs(IBootInstall bootInstall, ILaunch launch, ILaunchConfiguration configuration) { try { CloudCliInstall cloudCliInstall = bootInstall.getExtension(CloudCliInstall.class); if (cloudCliInstall == null) { Log.error("No Spring Cloud CLI installation found"); } else { String serviceId = configuration.getAttribute(ATTR_CLOUD_SERVICE_ID, (String) null); Version cloudCliVersion = cloudCliInstall.getVersion(); List vmArgs = new ArrayList<>(); List args = new ArrayList<>(); args.add(CloudCliInstall.COMMAND_PREFIX); args.add(serviceId); if (cloudCliVersion != null && SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { args.add("--deployer=thin"); } args.add("--"); args.add("--logging.level.org.springframework.cloud.launcher.deployer=DEBUG"); // VM argument for the service log output if (BootLaunchConfigurationDelegate.supportsAnsiConsoleOutput()) { vmArgs.add("-Dspring.output.ansi.enabled=always"); } if (CloudCliServiceLaunchConfigurationDelegate.SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.spring.cloud.deployer.local.javaOpts=" + String.join(",", vmArgs)); } } else if (CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion)) { int jmxPort = getJmxPort(configuration); // Set the JMX port for launch launch.setAttribute(BootLaunchConfigurationDelegate.JMX_PORT, String.valueOf(jmxPort)); vmArgs.addAll(getCloudCliServiceLifeCycleVmArguments(configuration, jmxPort)); // Set the JMX port connection jvm args for the service if (!vmArgs.isEmpty()) { args.add("--spring.cloud.launcher.deployables." + serviceId + ".properties.JAVA_OPTS=" + String.join(",", vmArgs)); } } return args.toArray(new String[args.size()]); } } catch (Exception e) { Log.log(e); } return new String[0]; } private int getJmxPort(ILaunchConfiguration configuration) { int port = 0; try { port = Integer.parseInt(BootLaunchConfigurationDelegate.getJMXPort(configuration)); } catch (Exception e) { // ignore: bad data in launch config. } if (port == 0) { try { // slightly better than calling JmxBeanSupport.randomPort() port = PortFinder.findFreePort(); } catch (IOException e) { Log.log(e); } } return port; } public static boolean isLocalCloudServiceLaunch(ILaunchConfiguration conf) { try { if (conf!=null) { String type = conf.getType().getIdentifier(); return TYPE_ID.equals(type); } } catch (Exception e) { Log.log(e); } return false; } public static ILaunchConfigurationWorkingCopy createLaunchConfig(String serviceId) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(TYPE_ID); ILaunchConfigurationWorkingCopy config = type.newInstance(null, serviceId); // Set default config with life cycle tracking support because it should cover with life cycle tracking and without BootLaunchConfigurationDelegate.setDefaults(config, null, null); config.setAttribute(ATTR_CLOUD_SERVICE_ID, serviceId); // Overwrite process factory class because for latest version of Cloud CLI life cycle tracking through JMX port is not available for services BootLaunchConfigurationDelegate.setProcessFactory(config, CloudCliProcessFactory.class); return config; } public static boolean canUseLifeCycle(ILaunch launch) { ILaunchConfiguration conf = launch.getLaunchConfiguration(); return conf!=null && canUseLifeCycle(conf); } public static boolean isSingleProcessServiceConfig(ILaunchConfiguration conf) { try { if (isCloudCliService(conf)) { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion); } } } catch (Exception e) { // ignore } return false; } public static boolean isCloudCliService(ILaunchConfiguration conf) { try { return TYPE_ID.equals(conf.getType().getIdentifier()); } catch (CoreException e) { // Ignore } return false; } public static boolean canUseLifeCycle(ILaunchConfiguration conf) { try { if (!isCloudCliService(conf)) { return false; } IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall == null) { return false; } Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (!canUseLifeCycle(cloudCliVersion)) { return false; } return SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion) || BootLaunchConfigurationDelegate.getEnableLifeCycle(conf); } catch (Exception e) { // Ignore } return false; } private static boolean canUseLifeCycle(Version cloudCliVersion) { // Cloud CLI version below 1.2.0 and over 1.3.0 can't have JMX connection to cloud service hence life cycle should be disabled. if (cloudCliVersion == null || !CloudCliInstall.CLOUD_CLI_JAVA_OPTS_SUPPORTING_VERSIONS.includes(cloudCliVersion) || SPRING_CLOUD_CLI_SINGLE_PROCESS_VERSION_RANGE.includes(cloudCliVersion)) { return false; } return true; } public static class CloudCliProcessFactory extends BootProcessFactory { @Override public IProcess newProcess(ILaunch launch, Process process, String label, Map attributes) { try { IBootInstall bootInstall = BootInstallManager.getInstance().getDefaultInstall(); if (bootInstall != null) { Version cloudCliVersion = bootInstall.getExtension(CloudCliInstall.class) == null ? null : bootInstall.getExtension(CloudCliInstall.class).getVersion(); if (CloudCliServiceLaunchConfigurationDelegate.isSingleProcessServiceConfig(launch.getLaunchConfiguration())) { final IPreferenceStore store = BootActivator.getDefault().getPreferenceStore(); // Set invalid PID initially thus if PID is failed to be calculated then set PID launch attribute to invalid PID to fallback to default non-JMX process tracking long pid = -1; try { if (ProcessUtils.isLatestJdkForTools()) { pid = ProcessUtils.getProcessID(process); } else { Log.warn("Old JDK version. Need latest JDK to make JMX connection to process using its PID"); if (!store.getBoolean(PREF_DONT_SHOW_JDK_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS runnning on an old JDK version. Point STS to the latest JDK and restart it to have complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JDK_WARNING, dialog.getToggleState()); }); } } } catch (NoClassDefFoundError e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_JRE_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable because STS is running on a JRE. Point it to a JDK and restart STS for complete service process life-cycle and port data", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_JRE_WARNING, dialog.getToggleState()); }); } } catch (UnsupportedOperationException e) { Log.warn(e); if (!store.getBoolean(PREF_DONT_SHOW_PLATFORM_WARNING)) { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning( Display.getCurrent().getActiveShell(), "Cloud CLI Service Info Limitation", "Cloud service process life-cycle data is limited and port data is unavailable on the current platform.", "Don't show this message again", false, null, null); store.setValue(PREF_DONT_SHOW_PLATFORM_WARNING, dialog.getToggleState()); }); } } launch.setAttribute(BootLaunchConfigurationDelegate.PROCESS_ID, String.valueOf(pid)); return new RuntimeProcess(launch, process, label, attributes); } else if (canUseLifeCycle(cloudCliVersion)) { return super.newProcess(launch, process, label, attributes); } } } catch (Exception e) { Log.log(e); } return new RuntimeProcess(launch, process, label, attributes); } } }
blob data class t t f data class blob 0 7006 https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.boot.launch/src/org/springframework/ide/eclipse/boot/launch/cli/CloudCliServiceLaunchConfigurationDelegate.java/#L54-L297 1 744 7006
1845 { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); }
long method Long Method, Data Class t f t  Data Class   0 12164 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 1 1845 12164
1593   YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Large Class 4. Feature Envy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } }
blob  Long method2 Data class3 Large Class4 Feature Envy t f f . Long method2. Data class3. Large Class4. Feature Envy blob 0 11406 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 2 1593 11406
1512 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; }
feature envy long method, data class t t f long method, data class feature envy 0 11160 https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 1 1512 11160
51 {"answer": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ForeachCommand extends Command { public static String[] foreachArgs = null; public ForeachCommand() { addCommand("foreach", "", "build up a list of elements to operate on "); addCommand("do", "", "repeat a command for each element in the list"); } public void run(String command, final String[] args, final Context context, final PrintStream out) throws DDRInteractiveCommandException { if (command.equals("!do")) { boolean echo = false; boolean quiet = false; String token = null; int commandIndex = 0; while (commandIndex < args.length) { if (args[commandIndex].equals("help")) { out.println("The !do command is used to repeat a command on the elements gathered by the !foreach command."); out.println("Syntax: !do [echo] [quiet] [token=] [args]"); out.println(); out.println("\techo\t\tOutput each command before it is run."); out.println("\tquiet\t\tSuppress delimiters between command outputs."); out.println("\ttoken=\tSpecify a substitution token. Occurrencs of this string in the args will be replaced by the current element."); return; } else if (args[commandIndex].equals("echo")) { echo = true; commandIndex += 1; } else if (args[commandIndex].equals("quiet")) { quiet = true; commandIndex += 1; } else if (args[commandIndex].startsWith("token=")) { token = args[commandIndex].substring("token=".length()); commandIndex += 1; } else { break; } } if (commandIndex >= args.length) { out.println("The do command requires another command to repeat."); return; } if ((null == foreachArgs) || (0 == foreachArgs.length)) { out.println("Element list is empty. Use the foreach command to populate it."); return; } for (int i = 0; i < foreachArgs.length; i++) { if (!quiet && (i > 0)) { out.println("========================================"); } try { String[] newArgs; if (null == token) { newArgs = substituteArgs(args, commandIndex, i); } else { newArgs = substituteArgs(args, commandIndex, i, token); } if (echo) { System.out.println("> " + args[commandIndex] + " " + Arrays.toString(newArgs)); } CommandParser commandParser = new CommandParser(args[commandIndex], newArgs); context.execute(commandParser, out); } catch (ParseException e) { e.printStackTrace(out); } catch (Throwable th) { out.println("Exception while executing " + args[commandIndex] + " " + foreachArgs[i]); th.printStackTrace(out); } } } else if(command.equals("!foreach")) { if (args.length > 0) { out.println("The !foreach command takes no arguments, but will read lines from the console until it encounters a blank line."); out.println("These lines can then be used as arguments to commands specified using !do."); return; } ArrayList lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (0 == line.length()) { break; } else { lines.add(line); } } // split by , String[] newArgs = new String[lines.size()]; lines.toArray(newArgs); foreachArgs = newArgs; } } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex) { /* Concatenate: * */ String[] newArgs = new String[args.length - commandIndex]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); newArgs[newArgs.length - 1] = foreachArgs[foreachIndex]; return newArgs; } private String[] substituteArgs(String[] args, int commandIndex, int foreachIndex, String token) { /* Concatenate: * * Replacing any occurence of token with */ String[] newArgs = new String[args.length - commandIndex - 1]; System.arraycopy(args, commandIndex + 1, newArgs, 0, args.length - commandIndex - 1); for (int i = 0; i < newArgs.length; i++) { newArgs[i] = newArgs[i].replace(token, foreachArgs[foreachIndex]); } return newArgs; } }
blob long method, data class t t f long method, data class blob 0 872 https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/tools/ddrinteractive/commands/ForeachCommand.java/#L37-L165 1 51 872
4334   { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; }
long method data class, long method t t t data class   0 11444 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 1 4334 11444
1468 YES I found bad smells the bad smells are: 1. Long method 2. Complex method 3. Data class 4. Primitive obsession 5. Feature envy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } }
blob  Long method 2 Complex method 3 Data class 4 Primitive obsession 5 Feature envy t f f . Long method 2. Complex method 3. Data class 4. Primitive obsession 5. Feature envy blob 0 11044 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 2 1468 11044
553  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; }
blob long method, data class t t f long method, data class blob 0 5576 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 1 553 5576
525 { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@UriEndpoint(firstVersion = "2.1.0", scheme = "quickfix", title = "QuickFix", syntax = "quickfix:configurationName", label = "messaging") public class QuickfixjEndpoint extends DefaultEndpoint implements QuickfixjEventListener, MultipleConsumersSupport { public static final String EVENT_CATEGORY_KEY = "EventCategory"; public static final String SESSION_ID_KEY = "SessionID"; public static final String MESSAGE_TYPE_KEY = "MessageType"; public static final String DATA_DICTIONARY_KEY = "DataDictionary"; private final QuickfixjEngine engine; private final List consumers = new CopyOnWriteArrayList<>(); @UriPath @Metadata(required = true) private String configurationName; @UriParam private SessionID sessionID; @UriParam private boolean lazyCreateEngine; public QuickfixjEndpoint(QuickfixjEngine engine, String uri, Component component) { super(uri, component); this.engine = engine; } public SessionID getSessionID() { return sessionID; } /** * The optional sessionID identifies a specific FIX session. The format of the sessionID is: * (BeginString):(SenderCompID)[/(SenderSubID)[/(SenderLocationID)]]->(TargetCompID)[/(TargetSubID)[/(TargetLocationID)]] */ public void setSessionID(SessionID sessionID) { this.sessionID = sessionID; } public String getConfigurationName() { return configurationName; } /** * The configFile is the name of the QuickFIX/J configuration to use for the FIX engine (located as a resource found in your classpath). */ public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } public boolean isLazyCreateEngine() { return lazyCreateEngine; } /** * This option allows to create QuickFIX/J engine on demand. * Value true means the engine is started when first message is send or there's consumer configured in route definition. * When false value is used, the engine is started at the endpoint creation. * When this parameter is missing, the value of component's property lazyCreateEngines is being used. */ public void setLazyCreateEngine(boolean lazyCreateEngine) { this.lazyCreateEngine = lazyCreateEngine; } @Override public Consumer createConsumer(Processor processor) throws Exception { log.info("Creating QuickFIX/J consumer: {}, ExchangePattern={}", sessionID != null ? sessionID : "No Session", getExchangePattern()); QuickfixjConsumer consumer = new QuickfixjConsumer(this, processor); configureConsumer(consumer); consumers.add(consumer); return consumer; } @Override public Producer createProducer() throws Exception { log.info("Creating QuickFIX/J producer: {}", sessionID != null ? sessionID : "No Session"); if (isWildcarded()) { throw new ResolveEndpointFailedException("Cannot create consumer on wildcarded session identifier: " + sessionID); } return new QuickfixjProducer(this); } @Override public boolean isSingleton() { return true; } @Override public void onEvent(QuickfixjEventCategory eventCategory, SessionID sessionID, Message message) throws Exception { if (this.sessionID == null || isMatching(sessionID)) { for (QuickfixjConsumer consumer : consumers) { Exchange exchange = QuickfixjConverters.toExchange(this, sessionID, message, eventCategory, getExchangePattern()); consumer.onExchange(exchange); if (exchange.getException() != null) { throw exchange.getException(); } } } } private boolean isMatching(SessionID sessionID) { if (this.sessionID.equals(sessionID)) { return true; } return isMatching(this.sessionID.getBeginString(), sessionID.getBeginString()) && isMatching(this.sessionID.getSenderCompID(), sessionID.getSenderCompID()) && isMatching(this.sessionID.getSenderSubID(), sessionID.getSenderSubID()) && isMatching(this.sessionID.getSenderLocationID(), sessionID.getSenderLocationID()) && isMatching(this.sessionID.getTargetCompID(), sessionID.getTargetCompID()) && isMatching(this.sessionID.getTargetSubID(), sessionID.getTargetSubID()) && isMatching(this.sessionID.getTargetLocationID(), sessionID.getTargetLocationID()); } private boolean isMatching(String s1, String s2) { return s1.equals("") || s1.equals("*") || s1.equals(s2); } private boolean isWildcarded() { if (sessionID == null) { return false; } return sessionID.getBeginString().equals("*") || sessionID.getSenderCompID().equals("*") || sessionID.getSenderSubID().equals("*") || sessionID.getSenderLocationID().equals("*") || sessionID.getTargetCompID().equals("*") || sessionID.getTargetSubID().equals("*") || sessionID.getTargetLocationID().equals("*"); } @Override public boolean isMultipleConsumersSupported() { return true; } /** * Initializing and starts the engine if it wasn't initialized so far. */ public void ensureInitialized() throws Exception { if (!engine.isInitialized()) { synchronized (engine) { if (!engine.isInitialized()) { engine.initializeEngine(); engine.start(); } } } } public QuickfixjEngine getEngine() { return engine; } @Override protected void doStop() throws Exception { // clear list of consumers consumers.clear(); } }
blob data class t t f data class blob 0 5430 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEndpoint.java/#L41-L194 1 525 5430
220 { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BookKeeper implements org.apache.bookkeeper.client.api.BookKeeper { private static final Logger LOG = LoggerFactory.getLogger(BookKeeper.class); final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; // The stats logger for this client. private final StatsLogger statsLogger; private final BookKeeperClientStats clientStats; // whether the event loop group is one we created, or is owned by whoever // instantiated us boolean ownEventLoopGroup = false; final BookieClient bookieClient; final BookieWatcherImpl bookieWatcher; final OrderedExecutor mainWorkerPool; final OrderedScheduler scheduler; final HashedWheelTimer requestTimer; final boolean ownTimer; final FeatureProvider featureProvider; final ScheduledExecutorService bookieInfoScheduler; final MetadataClientDriver metadataDriver; // Ledger manager responsible for how to store ledger meta data final LedgerManagerFactory ledgerManagerFactory; final LedgerManager ledgerManager; final LedgerIdGenerator ledgerIdGenerator; // Ensemble Placement Policy final EnsemblePlacementPolicy placementPolicy; BookieInfoReader bookieInfoReader; final ClientConfiguration conf; final ClientInternalConf internalConf; // Close State boolean closed = false; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); /** * BookKeeper Client Builder to build client instances. * * @see BookKeeperBuilder */ public static class Builder { final ClientConfiguration conf; ZooKeeper zk = null; EventLoopGroup eventLoopGroup = null; ByteBufAllocator allocator = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; DNSToSwitchMapping dnsResolver = null; HashedWheelTimer requestTimer = null; FeatureProvider featureProvider = null; Builder(ClientConfiguration conf) { this.conf = conf; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #eventLoopGroup(EventLoopGroup)} * @see #eventLoopGroup(EventLoopGroup) */ @Deprecated public Builder setEventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @deprecated since 4.5, use {@link #zk(ZooKeeper)} * @see #zk(ZooKeeper) */ @Deprecated public Builder setZookeeper(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @deprecated since 4.5, use {@link #statsLogger(StatsLogger)} * @see #statsLogger(StatsLogger) */ @Deprecated public Builder setStatsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client with a provided {@link EventLoopGroup}. * * @param f an external {@link EventLoopGroup} to use by the bookkeeper client. * @return client builder. * @since 4.5 */ public Builder eventLoopGroup(EventLoopGroup f) { eventLoopGroup = f; return this; } /** * Configure the bookkeeper client with a provided {@link ByteBufAllocator}. * * @param allocator an external {@link ByteBufAllocator} to use by the bookkeeper client. * @return client builder. * @since 4.9 */ public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } /** * Configure the bookkeeper client with a provided {@link ZooKeeper} client. * * @param zk an external {@link ZooKeeper} client to use by the bookkeeper client. * @return client builder. * @since 4.5 */ @Deprecated public Builder zk(ZooKeeper zk) { this.zk = zk; return this; } /** * Configure the bookkeeper client with a provided {@link StatsLogger}. * * @param statsLogger an {@link StatsLogger} to use by the bookkeeper client to collect stats generated * by the client. * @return client builder. * @since 4.5 */ public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } /** * Configure the bookkeeper client to use the provided dns resolver {@link DNSToSwitchMapping}. * * @param dnsResolver dns resolver for placement policy to use for resolving network locations. * @return client builder * @since 4.5 */ public Builder dnsResolver(DNSToSwitchMapping dnsResolver) { this.dnsResolver = dnsResolver; return this; } /** * Configure the bookkeeper client to use a provided {@link HashedWheelTimer}. * * @param requestTimer request timer for client to manage timer related tasks. * @return client builder * @since 4.5 */ public Builder requestTimer(HashedWheelTimer requestTimer) { this.requestTimer = requestTimer; return this; } /** * Feature Provider. * * @param featureProvider * @return */ public Builder featureProvider(FeatureProvider featureProvider) { this.featureProvider = featureProvider; return this; } public BookKeeper build() throws IOException, InterruptedException, BKException { checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, allocator, statsLogger, dnsResolver, requestTimer, featureProvider); } } public static Builder forConfig(final ClientConfiguration conf) { return new Builder(conf); } /** * Create a bookkeeper client. A zookeeper client and a client event loop group * will be instantiated as part of this constructor. * * @param servers * A list of one of more servers on which zookeeper is running. The * client assumes that the running bookies have been registered with * zookeeper under the path * {@link AbstractConfiguration#getZkAvailableBookiesPath()} * @throws IOException * @throws InterruptedException */ public BookKeeper(String servers) throws IOException, InterruptedException, BKException { this(new ClientConfiguration().setMetadataServiceUri("zk+null://" + servers + "/ledgers")); } /** * Create a bookkeeper client using a configuration object. * A zookeeper client and a client event loop group will be * instantiated as part of this constructor. * * @param conf * Client Configuration object * @throws IOException * @throws InterruptedException */ public BookKeeper(final ClientConfiguration conf) throws IOException, InterruptedException, BKException { this(conf, null, null, null, NullStatsLogger.INSTANCE, null, null, null); } private static ZooKeeper validateZooKeeper(ZooKeeper zk) throws NullPointerException, IOException { checkNotNull(zk, "No zookeeper instance provided"); if (!zk.getState().isConnected()) { LOG.error("Unconnected zookeeper handle passed to bookkeeper"); throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); } return zk; } private static EventLoopGroup validateEventLoopGroup(EventLoopGroup eventLoopGroup) throws NullPointerException { checkNotNull(eventLoopGroup, "No Event Loop Group provided"); return eventLoopGroup; } /** * Create a bookkeeper client but use the passed in zookeeper client instead * of instantiating one. * * @param conf * Client Configuration object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered * @throws IOException * @throws InterruptedException */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), null, null, NullStatsLogger.INSTANCE, null, null, null); } /** * Create a bookkeeper client but use the passed in zookeeper client and * client event loop group instead of instantiating those. * * @param conf * Client Configuration Object * {@link ClientConfiguration} * @param zk * Zookeeper client instance connected to the zookeeper with which * the bookies have registered. The ZooKeeper client must be connected * before it is passed to BookKeeper. Otherwise a KeeperException is thrown. * @param eventLoopGroup * An event loop group that will be used to create connections to the bookies * @throws IOException * @throws InterruptedException * @throws BKException in the event of a bookkeeper connection error */ public BookKeeper(ClientConfiguration conf, ZooKeeper zk, EventLoopGroup eventLoopGroup) throws IOException, InterruptedException, BKException { this(conf, validateZooKeeper(zk), validateEventLoopGroup(eventLoopGroup), null, NullStatsLogger.INSTANCE, null, null, null); } /** * Constructor for use with the builder. Other constructors also use it. */ @SuppressWarnings("deprecation") @VisibleForTesting BookKeeper(ClientConfiguration conf, ZooKeeper zkc, EventLoopGroup eventLoopGroup, ByteBufAllocator byteBufAllocator, StatsLogger rootStatsLogger, DNSToSwitchMapping dnsResolver, HashedWheelTimer requestTimer, FeatureProvider featureProvider) throws IOException, InterruptedException, BKException { this.conf = conf; // initialize feature provider if (null == featureProvider) { this.featureProvider = SettableFeatureProvider.DISABLE_ALL; } else { this.featureProvider = featureProvider; } this.internalConf = ClientInternalConf.fromConfigAndFeatureProvider(conf, this.featureProvider); // initialize resources this.scheduler = OrderedScheduler.newSchedulerBuilder().numThreads(1).name("BookKeeperClientScheduler").build(); this.mainWorkerPool = OrderedExecutor.newBuilder() .name("BookKeeperClientWorker") .numThreads(conf.getNumWorkerThreads()) .statsLogger(rootStatsLogger) .traceTaskExecution(conf.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(conf.getPreserveMdcForTaskExecution()) .traceTaskWarnTimeMicroSec(conf.getTaskExecutionWarnTimeMicros()) .enableBusyWait(conf.isBusyWaitEnabled()) .build(); // initialize stats logger this.statsLogger = rootStatsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE); this.clientStats = BookKeeperClientStats.newInstance(this.statsLogger); // initialize metadata driver try { String metadataServiceUriStr = conf.getMetadataServiceUri(); if (null != metadataServiceUriStr) { this.metadataDriver = MetadataDrivers.getClientDriver(URI.create(metadataServiceUriStr)); } else { checkNotNull(zkc, "No external zookeeper provided when no metadata service uri is found"); this.metadataDriver = MetadataDrivers.getClientDriver("zk"); } this.metadataDriver.initialize( conf, scheduler, rootStatsLogger, java.util.Optional.ofNullable(zkc)); } catch (ConfigurationException ce) { LOG.error("Failed to initialize metadata client driver using invalid metadata service uri", ce); throw new IOException("Failed to initialize metadata client driver", ce); } catch (MetadataException me) { LOG.error("Encountered metadata exceptions on initializing metadata client driver", me); throw new IOException("Failed to initialize metadata client driver", me); } // initialize event loop group if (null == eventLoopGroup) { this.eventLoopGroup = EventLoopUtil.getClientEventLoopGroup(conf, new DefaultThreadFactory("bookkeeper-io")); this.ownEventLoopGroup = true; } else { this.eventLoopGroup = eventLoopGroup; this.ownEventLoopGroup = false; } if (byteBufAllocator != null) { this.allocator = byteBufAllocator; } else { this.allocator = ByteBufAllocatorBuilder.create() .poolingPolicy(conf.getAllocatorPoolingPolicy()) .poolingConcurrency(conf.getAllocatorPoolingConcurrency()) .outOfMemoryPolicy(conf.getAllocatorOutOfMemoryPolicy()) .leakDetectionPolicy(conf.getAllocatorLeakDetectionPolicy()) .build(); } // initialize bookie client this.bookieClient = new BookieClientImpl(conf, this.eventLoopGroup, this.allocator, this.mainWorkerPool, scheduler, rootStatsLogger); if (null == requestTimer) { this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieClientTimer-%d").build(), conf.getTimeoutTimerTickDurationMs(), TimeUnit.MILLISECONDS, conf.getTimeoutTimerNumTicks()); this.ownTimer = true; } else { this.requestTimer = requestTimer; this.ownTimer = false; } // initialize the ensemble placement this.placementPolicy = initializeEnsemblePlacementPolicy(conf, dnsResolver, this.requestTimer, this.featureProvider, this.statsLogger); this.bookieWatcher = new BookieWatcherImpl( conf, this.placementPolicy, metadataDriver.getRegistrationClient(), this.statsLogger.scope(WATCHER_SCOPE)); if (conf.getDiskWeightBasedPlacementEnabled()) { LOG.info("Weighted ledger placement enabled"); ThreadFactoryBuilder tFBuilder = new ThreadFactoryBuilder() .setNameFormat("BKClientMetaDataPollScheduler-%d"); this.bookieInfoScheduler = Executors.newSingleThreadScheduledExecutor(tFBuilder.build()); this.bookieInfoReader = new BookieInfoReader(this, conf, this.bookieInfoScheduler); this.bookieWatcher.initialBlockingBookieRead(); this.bookieInfoReader.start(); } else { LOG.info("Weighted ledger placement is not enabled"); this.bookieInfoScheduler = null; this.bookieInfoReader = new BookieInfoReader(this, conf, null); this.bookieWatcher.initialBlockingBookieRead(); } // initialize ledger manager try { this.ledgerManagerFactory = this.metadataDriver.getLedgerManagerFactory(); } catch (MetadataException e) { throw new IOException("Failed to initialize ledger manager factory", e); } this.ledgerManager = new CleanupLedgerManager(ledgerManagerFactory.newLedgerManager()); this.ledgerIdGenerator = ledgerManagerFactory.newLedgerIdGenerator(); scheduleBookieHealthCheckIfEnabled(conf); } /** * Allow to extend BookKeeper for mocking in unit tests. */ @VisibleForTesting BookKeeper() { conf = new ClientConfiguration(); internalConf = ClientInternalConf.fromConfig(conf); statsLogger = NullStatsLogger.INSTANCE; clientStats = BookKeeperClientStats.newInstance(statsLogger); scheduler = null; requestTimer = null; metadataDriver = null; placementPolicy = null; ownTimer = false; mainWorkerPool = null; ledgerManagerFactory = null; ledgerManager = null; ledgerIdGenerator = null; featureProvider = null; eventLoopGroup = null; bookieWatcher = null; bookieInfoScheduler = null; bookieClient = null; allocator = UnpooledByteBufAllocator.DEFAULT; } private EnsemblePlacementPolicy initializeEnsemblePlacementPolicy(ClientConfiguration conf, DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, FeatureProvider featureProvider, StatsLogger statsLogger) throws IOException { try { Class policyCls = conf.getEnsemblePlacementPolicy(); return ReflectionUtils.newInstance(policyCls).initialize(conf, java.util.Optional.ofNullable(dnsResolver), timer, featureProvider, statsLogger); } catch (ConfigurationException e) { throw new IOException("Failed to initialize ensemble placement policy : ", e); } } int getReturnRc(int rc) { return getReturnRc(bookieClient, rc); } static int getReturnRc(BookieClient bookieClient, int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (bookieClient.isClosed()) { return BKException.Code.ClientClosedException; } else { return rc; } } } void scheduleBookieHealthCheckIfEnabled(ClientConfiguration conf) { if (conf.isBookieHealthCheckEnabled()) { scheduler.scheduleAtFixedRate(new SafeRunnable() { @Override public void safeRun() { checkForFaultyBookies(); } }, conf.getBookieHealthCheckIntervalSeconds(), conf.getBookieHealthCheckIntervalSeconds(), TimeUnit.SECONDS); } } void checkForFaultyBookies() { List faultyBookies = bookieClient.getFaultyBookies(); for (BookieSocketAddress faultyBookie : faultyBookies) { bookieWatcher.quarantineBookie(faultyBookie); } } /** * Returns ref to speculative read counter, needed in PendingReadOp. */ @VisibleForTesting public LedgerManager getLedgerManager() { return ledgerManager; } @VisibleForTesting LedgerManager getUnderlyingLedgerManager() { return ((CleanupLedgerManager) ledgerManager).getUnderlying(); } @VisibleForTesting LedgerIdGenerator getLedgerIdGenerator() { return ledgerIdGenerator; } @VisibleForTesting ReentrantReadWriteLock getCloseLock() { return closeLock; } @VisibleForTesting boolean isClosed() { return closed; } @VisibleForTesting BookieWatcher getBookieWatcher() { return bookieWatcher; } public OrderedExecutor getMainWorkerPool() { return mainWorkerPool; } @VisibleForTesting OrderedScheduler getScheduler() { return scheduler; } @VisibleForTesting EnsemblePlacementPolicy getPlacementPolicy() { return placementPolicy; } @VisibleForTesting public MetadataClientDriver getMetadataClientDriver() { return metadataDriver; } /** * There are 3 digest types that can be used for verification. The CRC32 is * cheap to compute but does not protect against byzantine bookies (i.e., a * bookie might report fake bytes and a matching CRC32). The MAC code is more * expensive to compute, but is protected by a password, i.e., a bookie can't * report fake bytes with a mathching MAC unless it knows the password. * The CRC32C, which use SSE processor instruction, has better performance than CRC32. * Legacy DigestType for backward compatibility. If we want to add new DigestType, * we should add it in here, client.api.DigestType and DigestType in DataFormats.proto. * If the digest type is set/passed in as DUMMY, a dummy digest is added/checked. * This DUMMY digest is mostly for test purposes or in situations/use-cases * where digest is considered a overhead. */ public enum DigestType { MAC, CRC32, CRC32C, DUMMY; public static DigestType fromApiDigestType(org.apache.bookkeeper.client.api.DigestType digestType) { switch (digestType) { case MAC: return DigestType.MAC; case CRC32: return DigestType.CRC32; case CRC32C: return DigestType.CRC32C; case DUMMY: return DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public static DataFormats.LedgerMetadataFormat.DigestType toProtoDigestType(DigestType digestType) { switch (digestType) { case MAC: return DataFormats.LedgerMetadataFormat.DigestType.HMAC; case CRC32: return DataFormats.LedgerMetadataFormat.DigestType.CRC32; case CRC32C: return DataFormats.LedgerMetadataFormat.DigestType.CRC32C; case DUMMY: return DataFormats.LedgerMetadataFormat.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + digestType); } } public org.apache.bookkeeper.client.api.DigestType toApiDigestType() { switch (this) { case MAC: return org.apache.bookkeeper.client.api.DigestType.MAC; case CRC32: return org.apache.bookkeeper.client.api.DigestType.CRC32; case CRC32C: return org.apache.bookkeeper.client.api.DigestType.CRC32C; case DUMMY: return org.apache.bookkeeper.client.api.DigestType.DUMMY; default: throw new IllegalArgumentException("Unable to convert digest type " + this); } } } ZooKeeper getZkHandle() { return ((ZKMetadataClientDriver) metadataDriver).getZk(); } protected ClientConfiguration getConf() { return conf; } StatsLogger getStatsLogger() { return statsLogger; } /** * Get the BookieClient, currently used for doing bookie recovery. * * @return BookieClient for the BookKeeper instance. */ BookieClient getBookieClient() { return bookieClient; } /** * Retrieves BookieInfo from all the bookies in the cluster. It sends requests * to all the bookies in parallel and returns the info from the bookies that responded. * If there was an error in reading from any bookie, nothing will be returned for * that bookie in the map. * @return map * A map of bookieSocketAddress to its BookiInfo * @throws BKException * @throws InterruptedException */ public Map getBookieInfo() throws BKException, InterruptedException { return bookieInfoReader.getBookieInfo(); } /** * Creates a new ledger asynchronously. To create a ledger, we need to specify * the ensemble size, the quorum size, the digest type, a password, a callback * implementation, and an optional control object. The ensemble size is how * many bookies the entries should be striped among and the quorum size is the * degree of replication of each entry. The digest type is either a MAC or a * CRC. Note that the CRC option is not able to protect a client against a * bookie that replaces an entry. The password is used not only to * authenticate access to a ledger, but also to verify entries in ledgers. * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to. each of these bookies * must acknowledge the entry before the call is completed. * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx) { asyncCreateLedger(ensSize, writeQuorumSize, writeQuorumSize, digestType, passwd, cb, ctx, Collections.emptyMap()); } /** * Creates a new ledger asynchronously. Ledgers created with this call have * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiate(); } finally { closeLock.readLock().unlock(); } } /** * Creates a new ledger. Default of 3 servers, and quorum of 2 servers. * * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(DigestType digestType, byte passwd[]) throws BKException, InterruptedException { return createLedger(3, 2, digestType, passwd); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param qSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int qSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, qSize, qSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. Parameters match those of asyncCreateLedger * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateCallback result = new SyncCreateCallback(future); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[]) throws InterruptedException, BKException { return createLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, Collections.emptyMap()); } /** * Synchronous call to create ledger. * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdv * * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; } /** * Creates a new ledger asynchronously and returns {@link LedgerHandleAdv} * which can accept entryId. Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of {@link #asyncCreateLedger(int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(-1L); } finally { closeLock.readLock().unlock(); } } /** * Synchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Parameters must match those of asyncCreateLedgerAdvWithLedgerId * @param ledgerId * @param ensSize * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedgerAdv(final long ledgerId, int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map customMetadata) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncCreateAdvCallback result = new SyncCreateAdvCallback(future); /* * Calls asynchronous version */ asyncCreateLedgerAdv(ledgerId, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, result, null, customMetadata); LedgerHandle lh = SyncCallbackUtils.waitForResult(future); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } else if (ledgerId != lh.getId()) { LOG.error("Unexpected condition : Expected ledgerId: {} but got: {}", ledgerId, lh.getId()); throw BKException.create(BKException.Code.UnexpectedConditionException); } LOG.info("Ensemble: {} for ledger: {}", lh.getLedgerMetadata().getEnsembleAt(0L), lh.getId()); return lh; } /** * Asynchronously creates a new ledger using the interface which accepts a ledgerId as input. * This method returns {@link LedgerHandleAdv} which can accept entryId. * Ledgers created with this call have ability to accept * a separate write quorum and ack quorum size. The write quorum must be larger than * the ack quorum. * * Separating the write and the ack quorum allows the BookKeeper client to continue * writing when a bookie has failed but the failure has not yet been detected. Detecting * a bookie has failed can take a number of seconds, as configured by the read timeout * {@link ClientConfiguration#getReadTimeout()}. Once the bookie failure is detected, * that bookie will be removed from the ensemble. * * The other parameters match those of asyncCreateLedger * * @param ledgerId * ledger Id to use for the newly created ledger * @param ensSize * number of bookies over which to stripe entries * @param writeQuorumSize * number of bookies each entry will be written to * @param ackQuorumSize * number of bookies which must acknowledge an entry before the call is completed * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param cb * createCallback implementation * @param ctx * optional control object * @param customMetadata * optional customMetadata that holds user specified metadata */ public void asyncCreateLedgerAdv(final long ledgerId, final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats) .initiateAdv(ledgerId); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading. * * Opening a ledger with this method invokes fencing and recovery on the ledger * if the ledger has not been closed. Fencing will block all other clients from * writing to the ledger. Recovery will make sure that the ledger is closed * before reading from it. * * Recovery also makes sure that any entries which reached one bookie, but not a * quorum, will be replicated to a quorum of bookies. This occurs in cases were * the writer of a ledger crashes after sending a write request to one bookie but * before being able to send it to the rest of the bookies in the quorum. * * If the ledger is already closed, neither fencing nor recovery will be applied. * * @see LedgerHandle#asyncClose * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedger(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Open existing ledger asynchronously for reading, but it does not try to * recover the ledger if it is not yet closed. The application needs to use * it carefully, since the writer might have crashed and ledger will remain * unsealed forever if there is no external mechanism to detect the failure * of the writer and the ledger is not open in a safe manner, invoking the * recovery procedure. * * Opening a ledger without recovery does not fence the ledger. As such, other * clients can continue to write to the ledger. * * This method returns a read only ledger handle. It will not be possible * to add entries to the ledger. Any attempt to add entries will throw an * exception. * * Reads from the returned ledger will be able to read entries up until * the lastConfirmedEntry at the point in time at which the ledger was opened. * If an attempt is made to read beyond the ledger handle's LAC, an attempt is made * to get the latest LAC from bookies or metadata, and if the entry_id of the read request * is less than or equal to the new LAC, read will be allowed to proceed. * * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @param ctx * optional control object */ public void asyncOpenLedgerNoRecovery(final long lId, final DigestType digestType, final byte passwd[], final OpenCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.openComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerOpenOp(BookKeeper.this, clientStats, lId, digestType, passwd, cb, ctx).initiateWithoutRecovery(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous open ledger call. * * @see #asyncOpenLedger * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedger(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedger(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Synchronous, unsafe open ledger call. * * @see #asyncOpenLedgerNoRecovery * @param lId * ledger identifier * @param digestType * digest type, either MAC or CRC32 * @param passwd * password * @return a handle to the open ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle openLedgerNoRecovery(long lId, DigestType digestType, byte passwd[]) throws BKException, InterruptedException { CompletableFuture future = new CompletableFuture<>(); SyncOpenCallback result = new SyncOpenCallback(future); /* * Calls async open ledger */ asyncOpenLedgerNoRecovery(lId, digestType, passwd, result, null); return SyncCallbackUtils.waitForResult(future); } /** * Deletes a ledger asynchronously. * * @param lId * ledger Id * @param cb * deleteCallback implementation * @param ctx * optional control object */ public void asyncDeleteLedger(final long lId, final DeleteCallback cb, final Object ctx) { closeLock.readLock().lock(); try { if (closed) { cb.deleteComplete(BKException.Code.ClientClosedException, ctx); return; } new LedgerDeleteOp(BookKeeper.this, clientStats, lId, cb, ctx).initiate(); } finally { closeLock.readLock().unlock(); } } /** * Synchronous call to delete a ledger. Parameters match those of * {@link #asyncDeleteLedger(long, AsyncCallback.DeleteCallback, Object)} * * @param lId * ledgerId * @throws InterruptedException * @throws BKException */ public void deleteLedger(long lId) throws InterruptedException, BKException { CompletableFuture future = new CompletableFuture<>(); SyncDeleteCallback result = new SyncDeleteCallback(future); // Call asynchronous version asyncDeleteLedger(lId, result, null); SyncCallbackUtils.waitForResult(future); } /** * Check asynchronously whether the ledger with identifier lId * has been closed. * * @param lId ledger identifier * @param cb callback method */ public void asyncIsClosed(long lId, final IsClosedCallback cb, final Object ctx){ ledgerManager.readLedgerMetadata(lId).whenComplete((metadata, exception) -> { if (exception == null) { cb.isClosedComplete(BKException.Code.OK, metadata.getValue().isClosed(), ctx); } else { cb.isClosedComplete(BKException.getExceptionCode(exception), false, ctx); } }); } /** * Check whether the ledger with identifier lId * has been closed. * * @param lId * @return boolean true if ledger has been closed * @throws BKException */ public boolean isClosed(long lId) throws BKException, InterruptedException { final class Result { int rc; boolean isClosed; final CountDownLatch notifier = new CountDownLatch(1); } final Result result = new Result(); final IsClosedCallback cb = new IsClosedCallback(){ @Override public void isClosedComplete(int rc, boolean isClosed, Object ctx){ result.isClosed = isClosed; result.rc = rc; result.notifier.countDown(); } }; /* * Call asynchronous version of isClosed */ asyncIsClosed(lId, cb, null); /* * Wait for callback */ result.notifier.await(); if (result.rc != BKException.Code.OK) { throw BKException.create(result.rc); } return result.isClosed; } /** * Shuts down client. * */ @Override public void close() throws BKException, InterruptedException { closeLock.writeLock().lock(); try { if (closed) { return; } closed = true; } finally { closeLock.writeLock().unlock(); } // Close bookie client so all pending bookie requests would be failed // which will reject any incoming bookie requests. bookieClient.close(); try { // Close ledger manage so all pending metadata requests would be failed // which will reject any incoming metadata requests. ledgerManager.close(); ledgerIdGenerator.close(); } catch (IOException ie) { LOG.error("Failed to close ledger manager : ", ie); } // Close the scheduler scheduler.shutdown(); if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The scheduler did not shutdown cleanly"); } mainWorkerPool.shutdown(); if (!mainWorkerPool.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The mainWorkerPool did not shutdown cleanly"); } if (this.bookieInfoScheduler != null) { this.bookieInfoScheduler.shutdown(); if (!bookieInfoScheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("The bookieInfoScheduler did not shutdown cleanly"); } } if (ownTimer) { requestTimer.stop(); } if (ownEventLoopGroup) { eventLoopGroup.shutdownGracefully(); } this.metadataDriver.close(); } @Override public CreateBuilder newCreateLedgerOp() { return new LedgerCreateOp.CreateBuilderImpl(this); } @Override public OpenBuilder newOpenLedgerOp() { return new LedgerOpenOp.OpenBuilderImpl(this); } @Override public DeleteBuilder newDeleteLedgerOp() { return new LedgerDeleteOp.DeleteBuilderImpl(this); } private final ClientContext clientCtx = new ClientContext() { @Override public ClientInternalConf getConf() { return internalConf; } @Override public LedgerManager getLedgerManager() { return BookKeeper.this.getLedgerManager(); } @Override public BookieWatcher getBookieWatcher() { return BookKeeper.this.getBookieWatcher(); } @Override public EnsemblePlacementPolicy getPlacementPolicy() { return BookKeeper.this.getPlacementPolicy(); } @Override public BookieClient getBookieClient() { return BookKeeper.this.getBookieClient(); } @Override public OrderedExecutor getMainWorkerPool() { return BookKeeper.this.getMainWorkerPool(); } @Override public OrderedScheduler getScheduler() { return BookKeeper.this.getScheduler(); } @Override public BookKeeperClientStats getClientStats() { return clientStats; } @Override public boolean isClientClosed() { return BookKeeper.this.isClosed(); } @Override public ByteBufAllocator getByteBufAllocator() { return allocator; } }; ClientContext getClientCtx() { return clientCtx; } }
blob long method, data class t t f long method, data class blob 0 2393 https://github.com/apache/bookkeeper/blob/f26a4cae0e9205ad391c6d4d79f2937871864c28/bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookKeeper.java/#L103-L1511 1 220 2393
2316  {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; }
feature envy data class t t f data class feature envy 0 14118 https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 1 2316 14118
6 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; }
feature envy data class t t f data class feature envy 0 570 https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 1 6 570
2610 {"response":"YES I found bad smells","the bad smells are":["Blob","Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } }
blob blob, long method, data class t t t  long method, data class   0 15035 https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 1 2610 15035
3581 { "input": { "codeSmells": ["Blob", "Data Class", "Feature Envy", "Long Method"], "code": "public class MyClass {\n private int x;\n\n public void setX(int x) {\n this.x = x;\n }\n\n public int getX() {\n return x;\n }\n}" }, "output": { "message": "YES I found bad smells", "detectedCodeSmells": "the bad smells are: 3. Data Class" } } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
feature envy message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class t t f message: yes i found bad smells, detectedcodesmells: the bad smells are: 3. data class feature envy 0 7900 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/service/cpi/SharingRegistryService.java/#L41810-L41827 1 3581 7900
1580 {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; }
long method long method, data class t t t  data class   0 11359 https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 1 1580 11359
2591 { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } }
blob data class t t f data class blob 0 14999 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 1 2591 14999
669 { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 6552 https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Nimbus.java/#L6217-L6283 1 669 6552
4111  YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Data class (lack of encapsulation) 5. Spaghetti code (multiple levels of nesting) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; }
long method  Long method2 Duplicate code3 Feature envy4 Data class (lack of encapsulation)5 Spaghetti code (multiple levels of nesting) t f t     0 10827 https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 2 4111 10827
1713  {"response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class GlyphPainter2 extends GlyphView.GlyphPainter { public GlyphPainter2(TextLayout layout) { this.layout = layout; } /** * Create a painter to use for the given GlyphView. */ public GlyphView.GlyphPainter getPainter(GlyphView v, int p0, int p1) { return null; } /** * Determine the span the glyphs given a start location * (for tab expansion). This implementation assumes it * has no tabs (i.e. TextLayout doesn't deal with tab * expansion). */ public float getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) { if ((p0 == v.getStartOffset()) && (p1 == v.getEndOffset())) { return layout.getAdvance(); } int p = v.getStartOffset(); int index0 = p0 - p; int index1 = p1 - p; TextHitInfo hit0 = TextHitInfo.afterOffset(index0); TextHitInfo hit1 = TextHitInfo.beforeOffset(index1); float[] locs = layout.getCaretInfo(hit0); float x0 = locs[0]; locs = layout.getCaretInfo(hit1); float x1 = locs[0]; return (x1 > x0) ? x1 - x0 : x0 - x1; } public float getHeight(GlyphView v) { return layout.getAscent() + layout.getDescent() + layout.getLeading(); } /** * Fetch the ascent above the baseline for the glyphs * corresponding to the given range in the model. */ public float getAscent(GlyphView v) { return layout.getAscent(); } /** * Fetch the descent below the baseline for the glyphs * corresponding to the given range in the model. */ public float getDescent(GlyphView v) { return layout.getDescent(); } /** * Paint the glyphs for the given view. This is implemented * to only render if the Graphics is of type Graphics2D which * is required by TextLayout (and this should be the case if * running on the JDK). */ public void paint(GlyphView v, Graphics g, Shape a, int p0, int p1) { if (g instanceof Graphics2D) { Rectangle2D alloc = a.getBounds2D(); Graphics2D g2d = (Graphics2D)g; float y = (float) alloc.getY() + layout.getAscent() + layout.getLeading(); float x = (float) alloc.getX(); if( p0 > v.getStartOffset() || p1 < v.getEndOffset() ) { try { //TextLayout can't render only part of it's range, so if a //partial range is required, add a clip region. Shape s = v.modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, a); Shape savedClip = g.getClip(); g2d.clip(s); layout.draw(g2d, x, y); g.setClip(savedClip); } catch (BadLocationException e) {} } else { layout.draw(g2d, x, y); } } } public Shape modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) throws BadLocationException { int offs = pos - v.getStartOffset(); Rectangle2D alloc = a.getBounds2D(); TextHitInfo hit = (bias == Position.Bias.Forward) ? TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs); float[] locs = layout.getCaretInfo(hit); // vertical at the baseline, should use slope and check if glyphs // are being rendered vertically. Rectangle2D rect = new Rectangle2D.Float(); rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight()); return rect; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param v the view containing the view coordinates * @param x the X coordinate * @param y the Y coordinate * @param a the allocated region to render into * @param biasReturn either Position.Bias.Forward * or Position.Bias.Backward is returned as the * zero-th element of this array * @return the location within the model that best represents the * given point of view * @see View#viewToModel */ public int viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) { Rectangle2D alloc = (a instanceof Rectangle2D) ? (Rectangle2D)a : a.getBounds2D(); //Move the y co-ord of the hit onto the baseline. This is because TextLayout supports //italic carets and we do not. TextHitInfo hit = layout.hitTestChar(x - (float)alloc.getX(), 0); int pos = hit.getInsertionIndex(); if (pos == v.getEndOffset()) { pos--; } biasReturn[0] = hit.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward; return pos + v.getStartOffset(); } /** * Determines the model location that represents the * maximum advance that fits within the given span. * This could be used to break the given view. The result * should be a location just shy of the given advance. This * differs from viewToModel which returns the closest * position which might be proud of the maximum advance. * * @param v the view to find the model location to break at. * @param p0 the location in the model where the * fragment should start it's representation >= 0. * @param x the graphic location along the axis that the * broken view would occupy >= 0. This may be useful for * things like tab calculations. * @param len specifies the distance into the view * where a potential break is desired >= 0. * @return the maximum model location possible for a break. * @see View#breakView */ public int getBoundedPosition(GlyphView v, int p0, float x, float len) { if( len < 0 ) throw new IllegalArgumentException("Length must be >= 0."); // note: this only works because swing uses TextLayouts that are // only pure rtl or pure ltr TextHitInfo hit; if (layout.isLeftToRight()) { hit = layout.hitTestChar(len, 0); } else { hit = layout.hitTestChar(layout.getAdvance() - len, 0); } return v.getStartOffset() + hit.getCharIndex(); } /** * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be * visible, they might not be in the same order found in the model, or * they just might not allow access to some of the locations in the * model. * * @param v the view to use * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { Document doc = v.getDocument(); int startOffset = v.getStartOffset(); int endOffset = v.getEndOffset(); Segment text; boolean viewIsLeftToRight; TextHitInfo currentHit, nextHit; switch (direction) { case View.NORTH: break; case View.SOUTH: break; case View.EAST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the left. if( viewIsLeftToRight ) { biasRet[0] = Position.Bias.Forward; return startOffset; } else { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { biasRet[0] = Position.Bias.Forward; return endOffset-1; } biasRet[0] = Position.Bias.Backward; return endOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextRightHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the right from an internal position will // only take us to the endOffset in a left to right run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; case View.WEST: viewIsLeftToRight = AbstractDocument.isLeftToRight(doc, startOffset, endOffset); if(startOffset == doc.getLength()) { if(pos == -1) { biasRet[0] = Position.Bias.Forward; return startOffset; } // End case for bidi text where newline is at beginning // of line. return -1; } if(pos == -1) { // Entering view from the right if( viewIsLeftToRight ) { text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if ((c == '\n') || Character.isSpaceChar(c)) { biasRet[0] = Position.Bias.Forward; return endOffset - 1; } biasRet[0] = Position.Bias.Backward; return endOffset; } else { biasRet[0] = Position.Bias.Forward; return startOffset; } } if( b==Position.Bias.Forward ) currentHit = TextHitInfo.afterOffset(pos-startOffset); else currentHit = TextHitInfo.beforeOffset(pos-startOffset); nextHit = layout.getNextLeftHit(currentHit); if( nextHit == null ) { return -1; } if( viewIsLeftToRight != layout.isLeftToRight() ) { // If the layout's base direction is different from // this view's run direction, we need to use the weak // carrat. nextHit = layout.getVisualOtherHit(nextHit); } pos = nextHit.getInsertionIndex() + startOffset; if(pos == endOffset) { // A move to the left from an internal position will // only take us to the endOffset in a right to left run. text = v.getText(endOffset - 1, endOffset); char c = text.array[text.offset]; SegmentCache.releaseSharedSegment(text); if(c == '\n') { return -1; } biasRet[0] = Position.Bias.Backward; } else { biasRet[0] = Position.Bias.Forward; } return pos; default: throw new IllegalArgumentException("Bad direction: " + direction); } return pos; } // --- variables --------------------------------------------- TextLayout layout; }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11775 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/GlyphPainter2.java/#L51-L385 1 1713 11775
707 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } }
blob data class, long method t t f data class, long method blob 0 6736 https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 1 707 6736
1455 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FlowFileUnpackagerV1 implements FlowFileUnpackager { private int flowFilesRead = 0; @Override public Map unpackageFlowFile(final InputStream in, final OutputStream out) throws IOException { flowFilesRead++; final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); final TarArchiveEntry attribEntry = tarIn.getNextTarEntry(); if (attribEntry == null) { return null; } final Map attributes; if (attribEntry.getName().equals(FlowFilePackagerV1.FILENAME_ATTRIBUTES)) { attributes = getAttributes(tarIn); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } final TarArchiveEntry contentEntry = tarIn.getNextTarEntry(); if (contentEntry != null && contentEntry.getName().equals(FlowFilePackagerV1.FILENAME_CONTENT)) { final byte[] buffer = new byte[512 << 10];//512KB int bytesRead = 0; while ((bytesRead = tarIn.read(buffer)) != -1) { //still more data to read if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } out.flush(); } else { throw new IOException("Expected two tar entries: " + FlowFilePackagerV1.FILENAME_CONTENT + " and " + FlowFilePackagerV1.FILENAME_ATTRIBUTES); } return attributes; } protected Map getAttributes(final TarArchiveInputStream stream) throws IOException { final Properties props = new Properties(); props.loadFromXML(new NonCloseableInputStream(stream)); final Map result = new HashMap<>(); for (final Entry entry : props.entrySet()) { final Object keyObject = entry.getKey(); final Object valueObject = entry.getValue(); if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains key of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } else if (!(keyObject instanceof String)) { throw new IOException("Flow file attributes object contains value of type " + keyObject.getClass().getCanonicalName() + " but expected java.lang.String"); } final String key = (String) keyObject; final String value = (String) valueObject; result.put(key, value); } return result; } @Override public boolean hasMoreData() throws IOException { return flowFilesRead == 0; } public static final class NonCloseableInputStream extends InputStream { final InputStream stream; public NonCloseableInputStream(final InputStream stream) { this.stream = stream; } @Override public void close() { } @Override public int read() throws IOException { return stream.read(); } @Override public int available() throws IOException { return stream.available(); } @Override public synchronized void mark(int readlimit) { stream.mark(readlimit); } @Override public synchronized void reset() throws IOException { stream.reset(); } @Override public boolean markSupported() { return stream.markSupported(); } @Override public long skip(long n) throws IOException { return stream.skip(n); } @Override public int read(byte b[], int off, int len) throws IOException { return stream.read(b, off, len); } @Override public int read(byte b[]) throws IOException { return stream.read(b); } } }
blob long method, data class t t f long method, data class blob 0 11008 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-flowfile-packager/src/main/java/org/apache/nifi/util/FlowFileUnpackagerV1.java/#L29-L155 1 1455 11008
275    { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.class, org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.Builder.class); } // Construct using org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); guaranteedTaskCount_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.internal_static_UpdateQueryRequestProto_descriptor; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto getDefaultInstanceForType() { return org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance(); } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto build() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto buildPartial() { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto result = new org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.guaranteedTaskCount_ = guaranteedTaskCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) { return mergeFrom((org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto other) { if (other == org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto.getDefaultInstance()) return this; if (other.hasGuaranteedTaskCount()) { setGuaranteedTaskCount(other.getGuaranteedTaskCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.hive.llap.plugin.rpc.LlapPluginProtocolProtos.UpdateQueryRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 guaranteed_task_count = 1; private int guaranteedTaskCount_ ; /** * optional int32 guaranteed_task_count = 1; */ public boolean hasGuaranteedTaskCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int32 guaranteed_task_count = 1; */ public int getGuaranteedTaskCount() { return guaranteedTaskCount_; } /** * optional int32 guaranteed_task_count = 1; */ public Builder setGuaranteedTaskCount(int value) { bitField0_ |= 0x00000001; guaranteedTaskCount_ = value; onChanged(); return this; } /** * optional int32 guaranteed_task_count = 1; */ public Builder clearGuaranteedTaskCount() { bitField0_ = (bitField0_ & ~0x00000001); guaranteedTaskCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:UpdateQueryRequestProto) }
blob long method, data class t t f long method, data class blob 0 2954 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/llap-common/src/gen/protobuf/gen-java/org/apache/hadoop/hive/llap/plugin/rpc/LlapPluginProtocolProtos.java/#L286-L435 1 275 2954
2499  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } }
long method long method, data class t t t  data class   0 14652 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 1 2499 14652
941  {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void setContentLength(final int length) { setIntHeader("Content-Length", length); }
feature envy data class t t f data class feature envy 0 8463 https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockHttpServletResponse.java/#L613-L617 1 941 8463
1721 {"answer":"YES I found bad smells","the bad smells are:":["1. Long method","2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 11796 https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 1 1721 11796
194 { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); }
blob data class, long method t t f data class, long method blob 0 2230 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 1 194 2230
149 {"response": "YES I found bad smells", "the bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class OgnlHelper { private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$"); private OgnlHelper() { } /** * Tests whether or not the given String is a Camel OGNL expression. * * An expression is considered an OGNL expression when it contains either one of the following chars: . or [ * * @param expression the String * @return true if a Camel OGNL expression, otherwise false. */ public static boolean isValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } // the brackets should come in a pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 && bracketEnd > 0) { return bracketBegin == bracketEnd; } return expression.contains("."); } public static boolean isInvalidValidOgnlExpression(String expression) { if (ObjectHelper.isEmpty(expression)) { return false; } if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) { return false; } // the brackets should come in pair int bracketBegin = StringHelper.countChar(expression, '['); int bracketEnd = StringHelper.countChar(expression, ']'); if (bracketBegin > 0 || bracketEnd > 0) { return bracketBegin != bracketEnd; } // check for double dots if (expression.contains("..")) { return true; } return false; } /** * Validates whether the method name is using valid java identifiers in the name * Will throw {@link IllegalArgumentException} if the method name is invalid. */ public static void validateMethodName(String method) { if (ObjectHelper.isEmpty(method)) { return; } for (int i = 0; i < method.length(); i++) { char ch = method.charAt(i); if (i == 0 && '.' == ch) { // its a dot before a method name continue; } if (ch == '(' || ch == '[' || ch == '.' || ch == '?') { // break when method name ends and sub method or arguments begin break; } if (i == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method); } } } /** * Tests whether or not the given Camel OGNL expression is using the null safe operator or not. * * @param ognlExpression the Camel OGNL expression * @return true if the null safe operator is used, otherwise false. */ public static boolean isNullSafeOperator(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return false; } return ognlExpression.startsWith("?"); } /** * Removes any leading operators from the Camel OGNL expression. * * Will remove any leading of the following chars: ? or . * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any leading operators. */ public static String removeLeadingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.startsWith("?")) { ognlExpression = ognlExpression.substring(1); } if (ognlExpression.startsWith(".")) { ognlExpression = ognlExpression.substring(1); } return ognlExpression; } /** * Removes any trailing operators from the Camel OGNL expression. * * @param ognlExpression the Camel OGNL expression * @return the Camel OGNL expression without any trailing operators. */ public static String removeTrailingOperators(String ognlExpression) { if (ObjectHelper.isEmpty(ognlExpression)) { return ognlExpression; } if (ognlExpression.contains("[")) { return StringHelper.before(ognlExpression, "["); } return ognlExpression; } public static String removeOperators(String ognlExpression) { return removeLeadingOperators(removeTrailingOperators(ognlExpression)); } public static KeyValueHolder isOgnlIndex(String ognlExpression) { Matcher matcher = INDEX_PATTERN.matcher(ognlExpression); if (matcher.matches()) { // to avoid empty strings as we want key/value to be null in such cases String key = matcher.group(1); if (ObjectHelper.isEmpty(key)) { key = null; } // to avoid empty strings as we want key/value to be null in such cases String value = matcher.group(2); if (ObjectHelper.isEmpty(value)) { value = null; } return new KeyValueHolder<>(key, value); } return null; } /** * Regular expression with repeating groups is a pain to get right * and then nobody understands the reg exp afterwards. * So we use a bit ugly/low-level Java code to split the OGNL into methods. * * @param ognl the ognl expression * @return a list of methods, will return an empty list, if ognl expression has no methods * @throws IllegalArgumentException if the last method has a missing ending parenthesis */ public static List splitOgnl(String ognl) { List methods = new ArrayList<>(); // return an empty list if ognl is empty if (ObjectHelper.isEmpty(ognl)) { return methods; } StringBuilder sb = new StringBuilder(); int j = 0; // j is used as counter per method boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo] boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo}) for (int i = 0; i < ognl.length(); i++) { char ch = ognl.charAt(i); // special for starting a new method if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?') || (ch != '.' && ch != '?' && ch != ']')) { sb.append(ch); // special if we are doing square bracket if (ch == '[' && !parenthesisBracket) { squareBracket = true; } else if (ch == '(') { parenthesisBracket = true; } else if (ch == ')') { parenthesisBracket = false; } j++; // advance } else { if (ch == '.' && !squareBracket && !parenthesisBracket) { // only treat dot as a method separator if not inside a square bracket block // as dots can be used in key names when accessing maps // a dit denotes end of this method and a new method is to be invoked String s = sb.toString(); // reset sb sb.setLength(0); // pass over ? to the new method if (s.endsWith("?")) { sb.append("?"); s = s.substring(0, s.length() - 1); } // add the method methods.add(s); // reset j to begin a new method j = 0; } else if (ch == ']' && !parenthesisBracket) { // append ending ] to method name sb.append(ch); String s = sb.toString(); // reset sb sb.setLength(0); // add the method methods.add(s); // reset j to begin a new method j = 0; // no more square bracket squareBracket = false; } // and don't lose the char if its not an ] end marker (as we already added that) if (ch != ']' || parenthesisBracket) { sb.append(ch); } // only advance if already begun on the new method if (j > 0) { j++; } } } // add remainder in buffer when reached end of data if (sb.length() > 0) { methods.add(sb.toString()); } String last = methods.isEmpty() ? null : methods.get(methods.size() - 1); if (parenthesisBracket && last != null) { // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis if (last.contains("(") && !last.endsWith(")")) { throw new IllegalArgumentException("Method should end with parenthesis, was " + last); } } return methods; } }
blob long method, data class t t f long method, data class blob 0 1873 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-util/src/main/java/org/apache/camel/util/OgnlHelper.java/#L27-L292 1 149 1873
2546   { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); }
feature envy data class, long method t t f data class, long method feature envy 0 14791 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 1 2546 14791
1569 {"answer": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } }
blob data class t t f data class blob 0 11334 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 1 1569 11334
2696 {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } }
long method long method, data class t t t  data class   0 15319 https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 1 2696 15319
1889 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } }
blob data class t t f data class blob 0 12304 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 1 1889 12304
1587 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } }
long method long method, data class t t t  data class   0 11373 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 1 1587 11373
542           { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 5540 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 1 542 5540
1837 { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } }
long method Long Method, Data Class t f t  Data Class   0 12142 https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 1 1837 12142
1798  { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component("org.apache.usergrid.rest.management.organizations.applications.ApplicationResource") @Scope("prototype") @Produces({ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", "text/jscript" }) public class ApplicationResource extends AbstractContextResource { private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); public static final String CONFIRM_APPLICATION_IDENTIFIER = "confirm_application_identifier"; public static final String RESTORE_PASSWORD = "restore_password"; //@Autowired //protected ExportService exportService; OrganizationInfo organization; UUID applicationId; ApplicationInfo application; @Autowired private SignInProviderFactory signInProviderFactory; public ApplicationResource() { } public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { this.organization = organization; this.applicationId = applicationId; return this; } public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { this.organization = organization; applicationId = application.getId(); this.application = application; return this; } @RequireOrganizationAccess @GET @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getApplication( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); ServiceManager sm = smf.getServiceManager( applicationId ); response.setAction( "get" ); response.setApplication( sm.getApplication() ); response.setParams( ui.getQueryParameters() ); response.setResults( management.getApplicationMetadata( applicationId ) ); return response; } @RequireOrganizationAccess @GET @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get application client credentials"); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.getClientSecretForApplication( applicationId ) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @POST @Path("credentials") @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse generateCredentials( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "generate application client credentials" ); ClientCredentialsInfo credentials = new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), management.newClientSecretForApplication(applicationId) ); response.setCredentials( credentials ); return response; } @RequireOrganizationAccess @GET @JSONP @Path("_size") public ApiResponse getApplicationSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "get application size for all entities" ); long size = management.getApplicationSize(this.applicationId); Map map = new HashMap<>(); Map innerMap = new HashMap<>(); Map sumMap = new HashMap<>(); innerMap.put("application",size); sumMap.put("size",innerMap); map.put("aggregation", sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("{collection_name}/_size") public ApiResponse getCollectionSize( @Context UriInfo ui, @PathParam( "collection_name" ) String collection_name, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); long size = management.getCollectionSize(this.applicationId, collection_name); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); Map innerMap = new HashMap<>(); innerMap.put(collection_name,size); sumMap.put("size",innerMap); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @RequireOrganizationAccess @GET @JSONP @Path("collections/_size") public ApiResponse getEachCollectionSize( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction("get collection size for all entities"); Map sizes = management.getEachCollectionSize(this.applicationId); Map map = new HashMap<>(); Map sumMap = new HashMap<>(); sumMap.put("size",sizes); map.put("aggregation",sumMap); response.setMetadata(map); return response; } @POST @Path("sia-provider") @Consumes(APPLICATION_JSON) @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, Map json, @QueryParam("callback") @DefaultValue("") String callback ) throws Exception { ApiResponse response = createApiResponse(); response.setAction( "post signin provider configuration" ); Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); SignInAsProvider signInAsProvider = null; if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { signInAsProvider = signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { signInAsProvider = signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); } else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { signInAsProvider = signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); } Preconditions.checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); signInAsProvider.saveToConfiguration( json ); return response; } // @POST // @Path("export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // // UUID jobUUID = null; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( bucketName == null ) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // json.put("organizationId", organization.getUuid()); // json.put( "applicationId",applicationId); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // catch ( Exception e ) { // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // return Response.status( SC_INTERNAL_SERVER_ERROR ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // @POST // @Path("collection/{collection_name}/export") // @Consumes(APPLICATION_JSON) // @RequireOrganizationAccess // public Response exportPostJson( @Context UriInfo ui, // @PathParam( "collection_name" ) String collection_name ,Map json, // @QueryParam("callback") @DefaultValue("") String callback ) // throws OAuthSystemException { // // UsergridAwsCredentials uac = new UsergridAwsCredentials(); // UUID jobUUID = null; // String colExport = collection_name; // Map uuidRet = new HashMap(); // // Map properties; // Map storage_info; // // try { // //checkJsonExportProperties(json); // if((properties = ( Map ) json.get( "properties" )) == null){ // throw new NullArgumentException("Could not find 'properties'"); // } // storage_info = ( Map ) properties.get( "storage_info" ); // String storage_provider = ( String ) properties.get( "storage_provider" ); // if(storage_provider == null) { // throw new NullArgumentException( "Could not find field 'storage_provider'" ); // } // if(storage_info == null) { // throw new NullArgumentException( "Could not find field 'storage_info'" ); // } // // String bucketName = ( String ) storage_info.get( "bucket_location" ); // String accessId = ( String ) storage_info.get( "s3_access_id" ); // String secretKey = ( String ) storage_info.get( "s3_key" ); // // if ( accessId == null ) { // throw new NullArgumentException( "Could not find field 's3_access_id'" ); // } // if ( secretKey == null ) { // throw new NullArgumentException( "Could not find field 's3_key'" ); // } // // if(bucketName == null) { // throw new NullArgumentException( "Could not find field 'bucketName'" ); // } // // json.put( "organizationId",organization.getUuid() ); // json.put( "applicationId", applicationId); // json.put( "collectionName", colExport); // // jobUUID = exportService.schedule( json ); // uuidRet.put( "Export Entity", jobUUID.toString() ); // } // catch ( NullArgumentException e ) { // return Response.status( SC_BAD_REQUEST ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ) // .build(); // } // catch ( Exception e ) { // // // TODO: throw descriptive error message and or include on in the response // // TODO: fix below, it doesn't work if there is an exception. // // Make it look like the OauthResponse. // // OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_INTERNAL_SERVER_ERROR ) // .setErrorDescription( e.getMessage() ) // .buildJSONMessage(); // // return Response.status( errorMsg.getResponseStatus() ) // .type( JSONPUtils.jsonMediaType( callback ) ) // .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ) // .build(); // } // // return Response.status( SC_ACCEPTED ).entity( uuidRet ).build(); // } // // // @Path( "imports" ) // public ImportsResource importGetJson( @Context UriInfo ui, // @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) // throws Exception { // // // return getSubResource( ImportsResource.class ).init( organization, application ); // } @GET @Path("/status") public Response getStatus() { Map statusMap = new HashMap(); EntityManager em = emf.getEntityManager( applicationId ); if ( !emf.getIndexHealth().equals( Health.RED ) ) { statusMap.put("message", "Index Health Status RED for application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } try { if ( em.getApplication() == null ) { statusMap.put("message", "Application " + applicationId + " not found"); return Response.status( SC_NOT_FOUND ).entity( statusMap ).build(); } } catch (Exception ex) { statusMap.put("message", "Error looking up application " + applicationId ); return Response.status( SC_INTERNAL_SERVER_ERROR ).entity( statusMap ).build(); } return Response.status( SC_OK ).entity( null ).build(); } /** * Put on application URL will restore application if it was deleted. */ @PUT @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executePut( @Context UriInfo ui, String body, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if ( applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (!SubjectUtils.isServiceAdmin()) { // require password if it exists String storedRestorePassword = restorePasswordService.getApplicationRestorePassword(applicationId); if (StringUtils.isNotEmpty(storedRestorePassword)) { // must have matching password as query parameter String suppliedRestorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (!storedRestorePassword.equals(suppliedRestorePassword)) { throw new IllegalArgumentException("Application cannot be restored without application password"); } } } management.restoreApplication( applicationId ); // not deleting password -- will be changed upon successful soft delete ApiResponse response = createApiResponse(); response.setAction( "restore" ); response.setApplication( emf.getEntityManager( applicationId ).getApplication() ); response.setParams( ui.getQueryParameters() ); return response; } /** * Caller MUST pass confirm_application_identifier that is either the UUID or the * name of the application to be deleted. Yes, this is redundant and intended to * be a protection measure to force caller to confirm that they want to do a delete. */ @DELETE @RequireOrganizationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse executeDelete( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback, @QueryParam(CONFIRM_APPLICATION_IDENTIFIER) String confirmApplicationIdentifier) throws Exception { if ( application == null && applicationId == null ) { throw new IllegalArgumentException("Application ID not specified in request"); } // If the path uses name then expect name, otherwise if they use uuid then expect uuid. if (application == null) { if (!applicationId.toString().equals( confirmApplicationIdentifier )) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application id."); } } else if (!application.getName().split( "/" )[1].equals( confirmApplicationIdentifier ) ) { throw new IllegalArgumentException( "Cannot delete application without supplying correct application name"); } String restorePassword = null; ApplicationRestorePasswordService restorePasswordService = getApplicationRestorePasswordService(); if (SubjectUtils.isServiceAdmin()) { restorePassword = ui.getQueryParameters().getFirst(RESTORE_PASSWORD); if (StringUtils.isNotEmpty(restorePassword)) { // save password, required for future undelete if not sysadmin restorePasswordService.setApplicationRestorePassword(applicationId, restorePassword); } } management.deleteApplication( applicationId ); if (restorePassword == null) { // clear restore password restorePasswordService.removeApplicationRestorePassword(applicationId); } if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() deleted appId = {}", applicationId); } ApiResponse response = createApiResponse(); response.setAction( "delete" ); response.setApplication(emf.getEntityManager( applicationId ).getApplication()); response.setParams(ui.getQueryParameters()); if (logger.isTraceEnabled()) { logger.trace("ApplicationResource.delete() sending response "); } return response; } private ApplicationRestorePasswordService getApplicationRestorePasswordService() { return injector.getInstance(ApplicationRestorePasswordService.class); } }
blob data class, long method t t f data class, long method blob 0 12006 https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/rest/src/main/java/org/apache/usergrid/rest/management/organizations/applications/ApplicationResource.java/#L63-L563 1 1798 12006
1977  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } }
blob data class, long method t t f data class, long method blob 0 12630 https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 1 1977 12630
2457      { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } }
blob data class, long method t t f data class, long method blob 0 14527 https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 1 2457 14527
870   YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Data class 5. Dead code 6. Inappropriate intimacy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public final class EclipseTeamProjectWizard extends EclipseConnectWizard implements ITeamProjectWizard { public static final CodeMarker CODEMARKER_NOTIFICATION_WIZARD_FINISH = new CodeMarker("com.microsoft.tfs.client.eclipse.ui.wizard.teamprojectwizard.EclipseTeamProjectWizard#finsh"); //$NON-NLS-1$ private static final Log log = LogFactory.getLog(EclipseTeamProjectWizard.class); private final static ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public EclipseTeamProjectWizard() { super( Messages.getString("EclipseTeamProjectWizard.WizardTitle"), //$NON-NLS-1$ Messages.getString("EclipseTeamProjectWizard.WizardDescription"), //$NON-NLS-1$ imageHelper.getImageDescriptor("images/wizard/pageheader.png"), //$NON-NLS-1$ SourceControlCapabilityFlags.GIT_TFS, ConnectWizard.PROJECT_SELECTION); addConnectionPages(); initConnectionPages(); if (hasPageData(Workspace.class)) { removePageData(Workspace.class); } } @Override public void setServerURI(final URI serverURI) { setPageData(URI.class, serverURI); } @Override public boolean enableNext(final IWizardPage currentPage) { if (!enableNextConnectionPage(currentPage)) { return false; } /* * Override super's behavior, if the current page is the team project * page, we don't want next to occur (hide the workspace page) */ if (getSelectionPageName().equals(currentPage.getName())) { return false; } return true; } @Override public IWizardPage getNextPage(final IWizardPage page) { final IWizardPage nextConnectionPage = getNextConnectionPage(); if (nextConnectionPage != null) { return nextConnectionPage; } /* * If we got to this point, then we were started from an already * connected state. This means that we only show the team project page. */ return getPage(getSelectionPageName()); } @Override protected boolean enableFinish(final IWizardPage currentPage) { /* * Finish is enabled for the team project page iff we already have a * workspace. */ if (getSelectionPageName().equals(currentPage.getName())) { return true; } return false; } @Override protected boolean doPerformFinish() { /* * Create a dummy server manager connection job for the UI - this will * prevent various views from saying "Not Connected" while we're hooking * up the various Plugin TFSServer and TFSRepository data in the * background. */ final IBackgroundTask backgroundTask = new BackgroundTask(Messages.getString("EclipseTeamProjectWizard.InitializingConnectionMessage")); //$NON-NLS-1$ TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskStarted(backgroundTask); try { final TFSTeamProjectCollection connection = (TFSTeamProjectCollection) getPageData(TFSTeamProjectCollection.class); /* See if there's an existing connection to a different server */ final TFSServer existingServer = TFSEclipseClientPlugin.getDefault().getServerManager().getDefaultServer(); /* See if there's an existing connection to a different workspace */ final TFSRepository existingRepository = TFSEclipseClientPlugin.getDefault().getRepositoryManager().getDefaultRepository(); final Workspace[] workspaces = getCurrentWorkspaces(connection); /* * If the user is connecting to a different server, then we prompt * them to close their existing mapped projects for this to * continue. */ if ((existingServer != null && !existingServer.connectionsEquivalent(connection))) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveServerConflict()) { CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } /* Ensure that the conflict was successfully resolved. */ if (TFSEclipseClientUIPlugin.getDefault().getServerManager().getDefaultServer() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyServerConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } /* * If the user is connecting to a different workspace, prompt to * close their existing mapped projects for this to continue. */ else if (workspaces != null && existingRepository != null) { boolean containsCurrentWorkspace = false; final Workspace currentWorkspace = existingRepository.getWorkspace(); for (final Workspace ws : workspaces) { if (currentWorkspace.equals(ws)) { containsCurrentWorkspace = true; } } if (!containsCurrentWorkspace) { if (!TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().resolveRepositoryConflict() || TFSEclipseClientUIPlugin.getDefault().getRepositoryManager().getDefaultRepository() != null) { TFSEclipseClientUIPlugin.getDefault().getConnectionConflictHandler().notifyRepositoryConflict(); CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return false; } } } finishConnection(); /* get the default workspace */ final Workspace workspace = getDefaultWorkspace(connection); finishWorkspace(workspace); } finally { TFSEclipseClientPlugin.getDefault().getServerManager().backgroundConnectionTaskFinished(backgroundTask); } CodeMarkerDispatch.dispatch(CODEMARKER_NOTIFICATION_WIZARD_FINISH); return true; } @Override public TFSServer getServer() { return (TFSServer) getPageData(TFSServer.class); } @Override public ProjectInfo[] getSelectedProjects() { return (ProjectInfo[]) getPageData(ConnectWizard.SELECTED_TEAM_PROJECTS); } }
blob  Long method2 Feature envy3 Duplicate code4 Data class5 Dead code6 Inappropriate intimacy t f f . Long method2. Feature envy3. Duplicate code4. Data class5. Dead code6. Inappropriate intimacy blob 0 7950 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.eclipse.ui/src/com/microsoft/tfs/client/eclipse/ui/wizard/teamprojectwizard/EclipseTeamProjectWizard.java/#L31-L196 2 870 7950
2064 { "output": "YES I found bad smells\nthe bad smells are: 1. Long method, 2. Data class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 12979 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 1 2064 12979
1741     { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11842 https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 1 1741 11842
1802 {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 12020 https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 1 1802 12020
1215          { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
// System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true;
long method blob, data class t t f blob, data class long method 0 10318 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 1 1215 10318
239      { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } }
blob data class t t f data class blob 0 2614 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 1 239 2614
2081 {"response": "YES I found bad smells", "the bad smells are": ["Long Method", "Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } }
blob long method, blob, data class t t t long method, data class   0 13072 https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 1 2081 13072
2668 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } }
blob data class t t f data class blob 0 15207 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 1 2668 15207
2174       { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Long parameter list", "Feature envy", "Data class", "Message chains", "Long class" ] } I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } }
blob long method, long parameter list, feature envy, data class, message chains, long class t t f long method, long parameter list, feature envy, data class, message chains, long class blob 0 13387 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 2 2174 13387
725   YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } }
blob  Long method2 Feature envy3 Data class4 Shotgun surgery t f f . Long method2. Feature envy3. Data class4. Shotgun surgery blob 0 6841 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 2 725 6841
2339 {"response": "YES I found bad smells the bad smells are: 1. Long method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } }
blob  Long method, 2 Data Class"} t f f . Long method, 2. Data Class"} blob 0 14172 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 1 2339 14172
2143 { "message": "YES I found bad smells", "the bad smells are:": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } }
blob data class, long method t t f data class, long method blob 0 13270 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 1 2143 13270
617 { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class", "2. Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface DbAction { Class getEntityType(); /** * Executing this DbAction with the given {@link Interpreter}. * * The default implementation just performs exception handling and delegates to {@link #doExecuteWith(Interpreter)}. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}.Must not be * {@code null}. */ default void executeWith(Interpreter interpreter) { try { doExecuteWith(interpreter); } catch (Exception e) { throw new DbActionExecutionException(this, e); } } /** * Executing this DbAction with the given {@link Interpreter} without any exception handling. * * @param interpreter the {@link Interpreter} responsible for actually executing the {@link DbAction}. */ void doExecuteWith(Interpreter interpreter); /** * Represents an insert statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data class Insert implements WithGeneratedId, WithDependingOn { @NonNull final T entity; @NonNull final PersistentPropertyPath propertyPath; @NonNull final WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } @Override public Class getEntityType() { return WithDependingOn.super.getEntityType(); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Data @RequiredArgsConstructor class InsertRoot implements WithEntity, WithGeneratedId { @NonNull private final T entity; private Object generatedId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an update statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Update implements WithEntity { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an insert statement for the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class UpdateRoot implements WithEntity { @NonNull private final T entity; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a merge statement for a single entity that is not the root of an aggregate. * * @param type of the entity for which this represents a database interaction. */ @Value class Merge implements WithDependingOn, WithPropertyPath { @NonNull T entity; @NonNull PersistentPropertyPath propertyPath; @NonNull WithEntity dependingOn; Map, Object> qualifiers = new HashMap<>(); @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all entities that that a reachable via a give path from the aggregate root. * * @param type of the entity for which this represents a database interaction. */ @Value class Delete implements WithPropertyPath { @NonNull Object rootId; @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for a aggregate root. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteRoot implements DbAction { @NonNull Class entityType; @NonNull Object rootId; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents an delete statement for all entities that that a reachable via a give path from any aggregate root of a * given type. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAll implements WithPropertyPath { @NonNull PersistentPropertyPath propertyPath; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * Represents a delete statement for all aggregate roots of a given type. * * Note that deletes for contained entities that reference the root are to be represented by separate * {@link DbAction}s. * * @param type of the entity for which this represents a database interaction. */ @Value class DeleteAllRoot implements DbAction { @NonNull private final Class entityType; @Override public void doExecuteWith(Interpreter interpreter) { interpreter.interpret(this); } } /** * An action depending on another action for providing additional information like the id of a parent entity. * * @author Jens Schauder */ interface WithDependingOn extends WithPropertyPath, WithEntity { /** * The {@link DbAction} of a parent entity, possibly the aggregate root. This is used to obtain values needed to * persist the entity, that are not part of the current entity, especially the id of the parent, which might only * become available once the parent entity got persisted. * * @return Guaranteed to be not {@code null}. * @see #getQualifiers() */ WithEntity getDependingOn(); /** * Additional values to be set during insert or update statements. * * Values come from parent entities but one might also add values manually. * * @return Guaranteed to be not {@code null}. */ Map, Object> getQualifiers(); @Override default Class getEntityType() { return WithEntity.super.getEntityType(); } } /** * A {@link DbAction} that stores the information of a single entity in the database. * * @author Jens Schauder */ interface WithEntity extends DbAction { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ T getEntity(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} that may "update" its entity. In order to support immutable entities this requires at least * potentially creating a new instance, which this interface makes available. * * @author Jens Schauder */ interface WithGeneratedId extends WithEntity { /** * @return the entity to persist. Guaranteed to be not {@code null}. */ @Nullable Object getGeneratedId(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getEntity().getClass(); } } /** * A {@link DbAction} not operation on the root of an aggregate but on its contained entities. * * @author Jens Schauder */ interface WithPropertyPath extends DbAction { /** * @return the path from the aggregate root to the affected entity */ PersistentPropertyPath getPropertyPath(); @SuppressWarnings("unchecked") @Override default Class getEntityType() { return (Class) getPropertyPath().getRequiredLeafProperty().getActualType(); } } }
blob 1. data class, 2. long method t t f 1. data class, 2. long method blob 0 6181 https://github.com/spring-projects/spring-data-jdbc/blob/913238a822ed04a24dd03cb704fd03a454d34c01/spring-data-relational/src/main/java/org/springframework/data/relational/core/conversion/DbAction.java/#L38-L328 1 617 6181
2145  {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; }
feature envy data class t t f data class feature envy 0 13274 https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 1 2145 13274
740   { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static class getJobSummary_resultStandardScheme extends StandardScheme { public void read(org.apache.thrift.protocol.TProtocol iprot, getJobSummary_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new Response(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getJobSummary_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 6974 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/client/sdk/ReadOnlyScheduler.java/#L3175-L3220 1 740 6974
1578   {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } }
blob data class t t f data class blob 0 11354 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 1 1578 11354
1288    { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); }
feature envy long method, data class t t f long method, data class feature envy 0 10614 https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 1 1288 10614
1863  YES I found bad smells the bad smells are: 1. Feature envy 2. Long method (renderStats()) 3. Data class (BoltExecutorStats) 4. Magic number (numStatBuckets, this.rate) 5. Dead code (renderStats() method has no actual implementation) 6. Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies()) 7. Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions) 8. Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods) 9. Inappropriate comments (comment just stating "common stats" in renderStats() method) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@SuppressWarnings("unchecked") public class BoltExecutorStats extends CommonStats { MultiCountStatAndMetric executedStats; MultiLatencyStatAndMetric processLatencyStats; MultiLatencyStatAndMetric executeLatencyStats; public BoltExecutorStats(int rate, int numStatBuckets) { super(rate, numStatBuckets); this.executedStats = new MultiCountStatAndMetric(numStatBuckets); this.processLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); this.executeLatencyStats = new MultiLatencyStatAndMetric(numStatBuckets); } public MultiCountStatAndMetric getExecuted() { return executedStats; } public MultiLatencyStatAndMetric getProcessLatencies() { return processLatencyStats; } public MultiLatencyStatAndMetric getExecuteLatencies() { return executeLatencyStats; } @Override public void cleanupStats() { executedStats.close(); processLatencyStats.close(); executeLatencyStats.close(); super.cleanupStats(); } public void boltExecuteTuple(String component, String stream, long latencyMs) { List key = Lists.newArrayList(component, stream); this.getExecuted().incBy(key, this.rate); this.getExecuteLatencies().record(key, latencyMs); } public void boltAckedTuple(String component, String stream, long latencyMs, Counter ackedCounter) { List key = Lists.newArrayList(component, stream); this.getAcked().incBy(key, this.rate); ackedCounter.inc(this.rate); this.getProcessLatencies().record(key, latencyMs); } public void boltFailedTuple(String component, String stream, long latencyMs, Counter failedCounter) { List key = Lists.newArrayList(component, stream); this.getFailed().incBy(key, this.rate); failedCounter.inc(this.rate); } @Override public ExecutorStats renderStats() { ExecutorStats ret = new ExecutorStats(); // common stats ret.set_emitted(valueStat(getEmitted())); ret.set_transferred(valueStat(getTransferred())); ret.set_rate(this.rate); // bolt stats BoltStats boltStats = new BoltStats( ClientStatsUtil.windowSetConverter(valueStat(getAcked()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(getFailed()), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(processLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executedStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY), ClientStatsUtil.windowSetConverter(valueStat(executeLatencyStats), ClientStatsUtil.TO_GSID, ClientStatsUtil.IDENTITY)); ret.set_specific(ExecutorSpecificStats.bolt(boltStats)); return ret; } }
blob  Feature envy2 Long method (renderStats())3 Data class (BoltExecutorStats)4 Magic number (numStatBuckets, thisrate)5 Dead code (renderStats() method has no actual implementation)6 Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies())7 Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions)8 Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods)9 Inappropriate comments (comment just stating "common stats" in renderStats() method) t f f . Feature envy2. Long method (renderStats())3. Data class (BoltExecutorStats)4. Magic number (numStatBuckets, this.rate)5. Dead code (renderStats() method has no actual implementation)6. Unnecessary getters and setters (getExecuted(), getProcessLatencies(), getExecuteLatencies())7. Inconsistent naming conventions (boltAckedTuple() and boltFailedTuple() methods have different naming conventions)8. Code duplication (same code in boltAckedTuple() and boltFailedTuple() methods)9. Inappropriate comments (comment just stating "common stats" in renderStats() method) blob 0 12226 https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/stats/BoltExecutorStats.java/#L24-L95 2 1863 12226
1604     { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); }
long method 1 Long Method, 2 Data Class t f t  2. Data Class   0 11442 https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 1 1604 11442
1971   YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Message chain, 4.Lazy class, 5.Magic number, 6.Unused code, 7.Commented-out code, 8.Data class. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } }
blob Long method, 2Feature envy, 3Message chain, 4Lazy class, 5Magic number, 6Unused code, 7Commented-out code, 8Data class t f f .Long method, 2.Feature envy, 3.Message chain, 4.Lazy class, 5.Magic number, 6.Unused code, 7.Commented-out code, 8.Data class. blob 0 12608 https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 2 1971 12608
2169 { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl
blob data class, long method t t f data class, long method blob 0 13355 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 1 2169 13355
1095  { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method", "Data Class" ] } } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } }
feature envy the bad smells are: long method, data class t t f the bad smells are: long method, data class feature envy 0 9781 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 1 1095 9781
1487 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class DocIdSetIterator { /** An empty {@code DocIdSetIterator} instance */ public static final DocIdSetIterator empty() { return new DocIdSetIterator() { boolean exhausted = false; @Override public int advance(int target) { assert !exhausted; assert target >= 0; exhausted = true; return NO_MORE_DOCS; } @Override public int docID() { return exhausted ? NO_MORE_DOCS : -1; } @Override public int nextDoc() { assert !exhausted; exhausted = true; return NO_MORE_DOCS; } @Override public long cost() { return 0; } }; } /** A {@link DocIdSetIterator} that matches all documents up to * {@code maxDoc - 1}. */ public static final DocIdSetIterator all(int maxDoc) { return new DocIdSetIterator() { int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { doc = target; if (doc >= maxDoc) { doc = NO_MORE_DOCS; } return doc; } @Override public long cost() { return maxDoc; } }; } /** A {@link DocIdSetIterator} that matches a range documents from * minDocID (inclusive) to maxDocID (exclusive). */ public static final DocIdSetIterator range(int minDoc, int maxDoc) { if (minDoc >= maxDoc) { throw new IllegalArgumentException("minDoc must be < maxDoc but got minDoc=" + minDoc + " maxDoc=" + maxDoc); } if (minDoc < 0) { throw new IllegalArgumentException("minDoc must be >= 0 but got minDoc=" + minDoc); } return new DocIdSetIterator() { private int doc = -1; @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { return advance(doc + 1); } @Override public int advance(int target) throws IOException { if (target < minDoc) { doc = minDoc; } else if (target >= maxDoc) { doc = NO_MORE_DOCS; } else { doc = target; } return doc; } @Override public long cost() { return maxDoc - minDoc; } }; } /** * When returned by {@link #nextDoc()}, {@link #advance(int)} and * {@link #docID()} it means there are no more docs in the iterator. */ public static final int NO_MORE_DOCS = Integer.MAX_VALUE; /** * Returns the following: * * -1 if {@link #nextDoc()} or * {@link #advance(int)} were not called yet. * {@link #NO_MORE_DOCS} if the iterator has exhausted. * Otherwise it should return the doc ID it is currently on. * * * * @since 2.9 */ public abstract int docID(); /** * Advances to the next document in the set and returns the doc it is * currently on, or {@link #NO_MORE_DOCS} if there are no more docs in the * set. * * NOTE: after the iterator has exhausted you should not call this * method, as it may result in unpredicted behavior. * * @since 2.9 */ public abstract int nextDoc() throws IOException; /** * Advances to the first beyond the current whose document number is greater * than or equal to target, and returns the document number itself. * Exhausts the iterator and returns {@link #NO_MORE_DOCS} if target * is greater than the highest document number in the set. * * The behavior of this method is undefined when called with * target ≤ current, or after the iterator has exhausted. * Both cases may result in unpredicted behavior. * * When target > current it behaves as if written: * * * int advance(int target) { * int doc; * while ((doc = nextDoc()) < target) { * } * return doc; * } * * * Some implementations are considerably more efficient than that. * * NOTE: this method may be called with {@link #NO_MORE_DOCS} for * efficiency by some Scorers. If your implementation cannot efficiently * determine that it should exhaust, it is recommended that you check for that * value in each call to this method. * * * @since 2.9 */ public abstract int advance(int target) throws IOException; /** Slow (linear) implementation of {@link #advance} relying on * {@link #nextDoc()} to advance beyond the target position. */ protected final int slowAdvance(int target) throws IOException { assert docID() < target; int doc; do { doc = nextDoc(); } while (doc < target); return doc; } /** * Returns the estimated cost of this {@link DocIdSetIterator}. * * This is generally an upper bound of the number of documents this iterator * might match, but may be a rough heuristic, hardcoded value, or otherwise * completely inaccurate. */ public abstract long cost(); }
blob data class, long method t t f data class, long method blob 0 11103 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java/#L29-L220 1 1487 11103
5309 { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob data class, long method t t f data class, long method blob 0 14864 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L72161-L72513 1 5309 14864
2010  { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class LayoutContext { /** * An {@link LayoutContext} notifies registered listeners about changes to * the layout algorithm using this property name. */ public static final String LAYOUT_ALGORITHM_PROPERTY = "layoutAlgorithm"; private ObjectProperty layoutAlgorithmProperty = new SimpleObjectProperty<>( this, LAYOUT_ALGORITHM_PROPERTY); private Graph graph; private final List postLayoutPass = new ArrayList<>(); private final List preLayoutPass = new ArrayList<>(); private final List layoutFilters = new ArrayList<>(); /** * Adds the given ILayoutFilter to this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to add to this context. */ public void addLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.add(layoutFilter); } /** * Applies the layout algorithm of this LayoutContext. The clean flag is * passed-in to the layout algorithm to indicate whether the context changed * significantly since the last layout pass. * * @param clear * true to indicate that the algorithm has to fully * re-compute the layout, otherwise false. */ public void applyLayout(boolean clear) { ILayoutAlgorithm layoutAlgorithm = layoutAlgorithmProperty.get(); if (layoutAlgorithm != null) { preLayout(); layoutAlgorithm.applyLayout(this, clear); postLayout(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run after the layout pass. Should not be * called by clients. */ public void postLayout() { for (Runnable r : new ArrayList<>(postLayoutPass)) { r.run(); } } /** * Initiated by the context or by an {@link ILayoutAlgorithm} to perform * steps that are scheduled to be run before the layout pass. Should not be * called by clients. */ public void preLayout() { for (Runnable r : preLayoutPass) { r.run(); } } /** * Returns the graph that is to be layouted. * * @return The {@link Graph} that is to be layouted. */ public Graph getGraph() { return graph; } /** * Sets the graph that is to be layouted by this context. * * @param graph * The {@link Graph} to layout. */ public void setGraph(Graph graph) { // TODO: we should not allow to pass in null here. Instead we should // guard ourselves against null. if (graph == null) { graph = new Graph(); } this.graph = graph; } /** * Returns all the nodes that should be laid out. Replacing elements in the * returned array does not affect this context. * * @return array of nodes to lay out */ // TODO: remove this (algorithms should use getGraph().getNodes()) public Node[] getNodes() { ObservableList nodes = graph.getNodes(); List layoutRelevantNodes = new ArrayList<>(); for (Node n : nodes) { if (!isLayoutIrrelevant(n)) { layoutRelevantNodes.add(n); } } return layoutRelevantNodes.toArray(new Node[] {}); } /** * Returns all the connections between nodes that should be laid out. * Replacing elements in the returned array does not affect this context. * * @return array of connections between nodes */ public Edge[] getEdges() { ObservableList edges = graph.getEdges(); List layoutRelevantEdges = new ArrayList<>(); for (Edge e : edges) { if (!isLayoutIrrelevant(e)) { layoutRelevantEdges.add(e); } } return layoutRelevantEdges.toArray(new Edge[] {}); } /** * Returns the static layout algorithm used to layout a newly initialized * graph or after heavy changes to it. * * @return The layout algorithm that is used by this {@link LayoutContext}. */ public ILayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithmProperty.get(); } /** * Returns true when the given {@link Edge} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param edge * The {@link Edge} in question. * @return true when the given {@link Edge} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Edge edge) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(edge)) { return true; } } return false; } /** * Returns true when the given {@link Node} is not relevant for * layout according to the configured {@link ILayoutFilter layout filters}. * Otherwise returns false. * * @param nodeLayout * The {@link Node} in question. * @return true when the given {@link Node} is not relevant for * layout according to the configure layout filters, otherwise * false. */ public boolean isLayoutIrrelevant(Node nodeLayout) { for (ILayoutFilter filter : layoutFilters) { if (filter.isLayoutIrrelevant(nodeLayout)) { return true; } } return false; } /** * A property representing the layout algorithm used by this * {@link LayoutContext}. * * @see #getLayoutAlgorithm() * @see #setLayoutAlgorithm(ILayoutAlgorithm) * * @return A property named {@link #LAYOUT_ALGORITHM_PROPERTY}. */ public ObjectProperty layoutAlgorithmProperty() { return layoutAlgorithmProperty; }; /** * Removes the given ILayoutFilter from this {@link LayoutContext}. * * @param layoutFilter * The ILayoutFilter to remove to this context. */ public void removeLayoutFilter(ILayoutFilter layoutFilter) { layoutFilters.remove(layoutFilter); } /** * Adds the given {@link Runnable} to the list of runnables which are called * when this {@link LayoutContext} is asked to apply all changes made to its * elements to the display. * * @param runnable * A {@link Runnable} called whenever this context is asked to * apply all changes made to its elements to the display. */ public void schedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!postLayoutPass.contains(runnable)) { postLayoutPass.add(runnable); } } /** * Adds the given {@link Runnable} to the list of {@link Runnable}s which * are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to add to the list of {@link Runnable}s * which are executed before applying a layout. */ public void schedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (!preLayoutPass.contains(runnable)) { preLayoutPass.add(runnable); } } /** * Sets the layout algorithm for this context. * * @param algorithm * The new {@link ILayoutAlgorithm} for this * {@link LayoutContext}. */ public void setLayoutAlgorithm(ILayoutAlgorithm algorithm) { layoutAlgorithmProperty.set(algorithm); } /** * Removes the given {@link Runnable} from the list of runnables which are * called when this {@link LayoutContext} is asked to apply all changes made * to its elements to the display. * * @param runnable * The {@link Runnable} that should no longer get called when * flushing changes. */ public void unschedulePostLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (postLayoutPass.contains(runnable)) { postLayoutPass.remove(runnable); } } /** * Removes the given {@link Runnable} from the list of {@link Runnable}s * which are executed before applying a layout, i.e. before * {@link #applyLayout(boolean)}. * * @param runnable * The {@link Runnable} to remove from the list of * {@link Runnable}s which are executed before applying a layout. */ public void unschedulePreLayoutPass(Runnable runnable) { if (runnable == null) { throw new IllegalArgumentException("Runnable may not be null."); } if (preLayoutPass.contains(runnable)) { preLayoutPass.remove(runnable); } } }
blob data class, long method t t f data class, long method blob 0 12748 https://github.com/eclipse/gef/blob/8f2649b90ab14a1bb010188036d4eedf7586e123/org.eclipse.gef.layout/src/org/eclipse/gef/layout/LayoutContext.java/#L35-L315 1 2010 12748
1627 {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } }
blob long method, data class t t f long method, data class blob 0 11501 https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 1 1627 11501
550  {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void uncompressed(Blackhole blackhole) { final ImmutableConciseSet set = ImmutableConciseSet.complement(null, emptyRows); blackhole.consume(set); assert (emptyRows == set.size()); }
feature envy long method, data class t t f long method, data class feature envy 0 5563 https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/benchmarks/src/main/java/org/apache/druid/benchmark/ConciseComplementBenchmark.java/#L43-L51 1 550 5563
1794   YES I found bad smells! The bad smells are: 1) Long method 2) Data Class 3) Long parameter list 4) Primitive Obsession 5) Inconsistent formatting 6) Redundant null check 7) Magic number 8) Feature envy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } }
blob ) Long method2) Data Class3) Long parameter list4) Primitive Obsession5) Inconsistent formatting6) Redundant null check7) Magic number8) Feature envy t f f ) Long method2) Data Class3) Long parameter list4) Primitive Obsession5) Inconsistent formatting6) Redundant null check7) Magic number8) Feature envy blob 0 11997 https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 2 1794 11997
1684   {"message": "YES I found bad smells", "bad smells are": ["2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } }
blob 2 Data Class t f f 2. Data Class blob 0 11684 https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 1 1684 11684
675    { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } }
blob long method, data class t t f long method, data class blob 0 6572 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 1 675 6572
2475   { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; }
long method long method, data class t t t  data class   0 14585 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 1 2475 14585
1702 { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } }
blob data class t t f data class blob 0 11737 https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 1 1702 11737
1723 { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11798 https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 1 1723 11798
2131    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } }
long method long method, data class t t t  data class   0 13232 https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 1 2131 13232
244 { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } }
blob long method, data class t t f long method, data class blob 0 2649 https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 1 244 2649
2382  { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl
blob long method, data class t t f long method, data class blob 0 14339 https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 1 2382 14339
572  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } }
blob data class t t f data class blob 0 5756 https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 1 572 5756
531  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } }
blob long method, data class t t f long method, data class blob 0 5477 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 1 531 5477
5298  {"answer":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component(service = RuleRegistry.class, immediate = true, property = { "rule.reinitialization.delay:Long=500" }) public class RuleRegistryImpl extends AbstractRegistry implements RuleRegistry, RegistryChangeListener { /** * Default value of delay between rule's re-initialization tries. */ private static final long DEFAULT_REINITIALIZATION_DELAY = 500; /** * Delay between rule's re-initialization tries. */ private static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay"; private static final String SOURCE = RuleRegistryImpl.class.getSimpleName(); private final Logger logger = LoggerFactory.getLogger(RuleRegistryImpl.class.getName()); /** * Delay between rule's re-initialization tries. */ private long scheduleReinitializationDelay; private ModuleTypeRegistry moduleTypeRegistry; private RuleTemplateRegistry templateRegistry; /** * {@link Map} of template UIDs to rules where these templates participated. */ private final Map> mapTemplateToRules = new HashMap>(); /** * Constructor that is responsible to invoke the super constructor with appropriate providerClazz * {@link RuleProvider} - the class of the providers that should be tracked automatically after activation. */ public RuleRegistryImpl() { super(RuleProvider.class); } /** * Activates this component. Called from DS. * * @param componentContext this component context. */ @Activate protected void activate(BundleContext bundleContext, Map properties) throws Exception { modified(properties); super.activate(bundleContext); } /** * This method is responsible for updating the value of delay between rule's re-initialization tries. * * @param config a {@link Map} containing the new value of delay. */ @Modified protected void modified(Map config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Override protected void setEventPublisher(EventPublisher eventPublisher) { super.setEventPublisher(eventPublisher); } @Override protected void unsetEventPublisher(EventPublisher eventPublisher) { super.unsetEventPublisher(eventPublisher); } @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, name = "ManagedRuleProvider") protected void setManagedProvider(ManagedRuleProvider managedProvider) { super.setManagedProvider(managedProvider); } protected void unsetManagedProvider(ManagedRuleProvider managedProvider) { super.unsetManagedProvider(managedProvider); } /** * Bind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = moduleTypeRegistry; } /** * Unbind the {@link ModuleTypeRegistry} service - called from DS. * * @param moduleTypeRegistry a {@link ModuleTypeRegistry} service. */ protected void unsetModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) { this.moduleTypeRegistry = null; } /** * Bind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC) protected void setTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = (RuleTemplateRegistry) templateRegistry; templateRegistry.addRegistryChangeListener(this); } } /** * Unbind the {@link RuleTemplateRegistry} service - called from DS. * * @param templateRegistry a {@link RuleTemplateRegistry} service. */ protected void unsetTemplateRegistry(TemplateRegistry templateRegistry) { if (templateRegistry instanceof RuleTemplateRegistry) { this.templateRegistry = null; templateRegistry.removeRegistryChangeListener(this); } } /** * This method is used to register a {@link Rule} into the {@link RuleEngineImpl}. First the {@link Rule} become * {@link RuleStatus#UNINITIALIZED}. * Then verification procedure will be done and the Rule become {@link RuleStatus#IDLE}. * If the verification fails, the Rule will stay {@link RuleStatus#UNINITIALIZED}. * * @param rule a {@link Rule} instance which have to be added into the {@link RuleEngineImpl}. * @return a copy of the added {@link Rule} * @throws RuntimeException * when passed module has a required configuration property and it is not specified * in rule definition * nor * in the module's module type definition. * @throws IllegalArgumentException * when a module id contains dot or when the rule with the same UID already exists. */ @Override public Rule add(Rule rule) { super.add(rule); Rule ruleCopy = get(rule.getUID()); if (ruleCopy == null) { throw new IllegalStateException(); } return ruleCopy; } @Override protected void notifyListenersAboutAddedElement(Rule element) { postRuleAddedEvent(element); postRuleStatusInfoEvent(element.getUID(), new RuleStatusInfo(RuleStatus.UNINITIALIZED)); super.notifyListenersAboutAddedElement(element); } @Override protected void notifyListenersAboutUpdatedElement(Rule oldElement, Rule element) { postRuleUpdatedEvent(element, oldElement); super.notifyListenersAboutUpdatedElement(oldElement, element); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleAddedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleAddedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleRemovedEvent(Rule rule) { postEvent(RuleEventFactory.createRuleRemovedEvent(rule, SOURCE)); } /** * @see RuleRegistryImpl#postEvent(org.eclipse.smarthome.core.events.Event) */ protected void postRuleUpdatedEvent(Rule rule, Rule oldRule) { postEvent(RuleEventFactory.createRuleUpdatedEvent(rule, oldRule, SOURCE)); } /** * This method can be used in order to post events through the Eclipse SmartHome events bus. A common * use case is to notify event subscribers about the {@link Rule}'s status change. * * @param ruleUID the UID of the {@link Rule}, whose status is changed. * @param statusInfo the new {@link Rule}s status. */ protected void postRuleStatusInfoEvent(String ruleUID, RuleStatusInfo statusInfo) { postEvent(RuleEventFactory.createRuleStatusInfoEvent(statusInfo, ruleUID, SOURCE)); } @Override protected void onRemoveElement(Rule rule) { String uid = rule.getUID(); String templateUID = rule.getTemplateUID(); if (templateUID != null) { updateRuleTemplateMapping(templateUID, uid, true); } } @Override protected void notifyListenersAboutRemovedElement(Rule element) { super.notifyListenersAboutRemovedElement(element); postRuleRemovedEvent(element); } @Override public Collection getByTag(String tag) { Collection result = new LinkedList(); if (tag == null) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().contains(tag)) { result.add(rule); } }); } return result; } @Override public Collection getByTags(String... tags) { Set tagSet = tags != null ? new HashSet(Arrays.asList(tags)) : null; Collection result = new LinkedList(); if (tagSet == null || tagSet.isEmpty()) { forEach(result::add); } else { forEach(rule -> { if (rule.getTags().containsAll(tagSet)) { result.add(rule); } }); } return result; } /** * The method checks if the rule has to be resolved by template or not. If the rule does not contain tempateUID it * returns same rule, otherwise it tries to resolve the rule created from template. If the template is available * the method creates a new rule based on triggers, conditions and actions from template. If the template is not * available returns the same rule. * * @param rule a rule defined by template. * @return the resolved rule(containing modules defined by the template) or not resolved rule, if the template is * missing. */ private Rule resolveRuleByTemplate(Rule rule) { String templateUID = rule.getTemplateUID(); if (templateUID == null) { return rule; } RuleTemplate template = templateRegistry.get(templateUID); String uid = rule.getUID(); if (template == null) { updateRuleTemplateMapping(templateUID, uid, false); logger.debug("Rule template {} does not exist.", templateUID); return rule; } else { RuleImpl resolvedRule = (RuleImpl) RuleBuilder .create(template, rule.getUID(), rule.getName(), rule.getConfiguration(), rule.getVisibility()) .build(); resolveConfigurations(resolvedRule); updateRuleTemplateMapping(templateUID, uid, true); return resolvedRule; } } /** * Updates the content of the {@link Map} that maps the template to rules, using it to complete their definitions. * * @param templateUID the {@link RuleTemplate}'s UID specifying the template. * @param ruleUID the {@link Rule}'s UID specifying a rule created by the specified template. * @param resolved specifies if the {@link Map} should be updated by adding or removing the specified rule * accordingly if the rule is resolved or not. */ private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { synchronized (this) { Set ruleUIDs = mapTemplateToRules.get(templateUID); if (ruleUIDs == null) { ruleUIDs = new HashSet(); mapTemplateToRules.put(templateUID, ruleUIDs); } if (resolved) { ruleUIDs.remove(ruleUID); } else { ruleUIDs.add(ruleUID); } } } @Override protected void addProvider(Provider provider) { super.addProvider(provider); forEach(provider, rule -> { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } }); } @Override public void added(Provider provider, Rule element) { String ruleUID = element.getUID(); Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", ruleUID, e); } super.added(provider, element); if (element != resolvedRule) { if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, element, resolvedRule); } } } @Override public void updated(Provider provider, Rule oldElement, Rule element) { String uid = element.getUID(); if (oldElement != null && uid.equals(oldElement.getUID())) { Rule resolvedRule = element; try { resolvedRule = resolveRuleByTemplate(element); } catch (IllegalArgumentException e) { logger.error("The rule '{}' is not updated, the new version is invalid", uid, e); } if (element != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { super.updated(provider, oldElement, resolvedRule); } } else { throw new IllegalArgumentException( String.format("The rule '%s' is not updated, not matching with any existing rule", uid)); } } @Override protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } } @Override protected void onUpdateElement(Rule oldElement, Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("The new version of updated rule '{}' is invalid", uid, e); } } /** * This method serves to resolve and normalize the {@link Rule}s configuration values and its module configurations. * * @param rule the {@link Rule}, whose configuration values and module configuration values should be resolved and * normalized. */ private void resolveConfigurations(Rule rule) { List configDescriptions = rule.getConfigurationDescriptions(); Configuration configuration = rule.getConfiguration(); ConfigurationNormalizer.normalizeConfiguration(configuration, ConfigurationNormalizer.getConfigDescriptionMap(configDescriptions)); Map configurationProperties = configuration.getProperties(); if (rule.getTemplateUID() == null) { String uid = rule.getUID(); try { validateConfiguration(configDescriptions, new HashMap<>(configurationProperties)); resolveModuleConfigReferences(rule.getModules(), configurationProperties); ConfigurationNormalizer.normalizeModuleConfigurations(rule.getModules(), moduleTypeRegistry); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("The rule '%s' has incorrect configurations", uid), e); } } } /** * This method serves to validate the {@link Rule}s configuration values. * * @param rule the {@link Rule}, whose configuration values should be validated. */ private void validateConfiguration(List configDescriptions, Map configurations) { if (configurations == null || configurations.isEmpty()) { if (isOptionalConfig(configDescriptions)) { return; } else { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (ConfigDescriptionParameter configParameter : configDescriptions) { if (configParameter.isRequired()) { String name = configParameter.getName(); statusDescription.append(String.format(msg, name)); } } throw new IllegalArgumentException( "Missing required configuration properties: " + statusDescription.toString()); } } else { for (ConfigDescriptionParameter configParameter : configDescriptions) { String configParameterName = configParameter.getName(); processValue(configurations.remove(configParameterName), configParameter); } if (!configurations.isEmpty()) { StringBuffer statusDescription = new StringBuffer(); String msg = " '%s';"; for (String name : configurations.keySet()) { statusDescription.append(String.format(msg, name)); } throw new IllegalArgumentException("Extra configuration properties: " + statusDescription.toString()); } } } /** * Utility method for {@link Rule}s configuration validation. * * @param configDescriptions the meta-data for {@link Rule}s configuration, used for validation. * @return {@code true} if all configuration properties are optional or {@code false} if there is at least one * required property. */ private boolean isOptionalConfig(List configDescriptions) { if (configDescriptions != null && !configDescriptions.isEmpty()) { boolean required = false; Iterator i = configDescriptions.iterator(); while (i.hasNext()) { ConfigDescriptionParameter param = i.next(); required = required || param.isRequired(); } return !required; } return true; } /** * Utility method for {@link Rule}s configuration validation. Validates the value of a configuration property. * * @param configValue the value for {@link Rule}s configuration property, that should be validated. * @param configParameter the meta-data for {@link Rule}s configuration value, used for validation. */ private void processValue(Object configValue, ConfigDescriptionParameter configParameter) { if (configValue != null) { Type type = configParameter.getType(); if (configParameter.isMultiple()) { if (configValue instanceof List) { @SuppressWarnings("rawtypes") List lConfigValues = (List) configValue; for (Object value : lConfigValues) { if (!checkType(type, value)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected type: " + type); } } } else { throw new IllegalArgumentException( "Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is Array with type for elements : " + type.toString() + "!"); } } else if (!checkType(type, configValue)) { throw new IllegalArgumentException("Unexpected value for configuration property \"" + configParameter.getName() + "\". Expected is " + type.toString() + "!"); } } else if (configParameter.isRequired()) { throw new IllegalArgumentException( "Required configuration property missing: \"" + configParameter.getName() + "\"!"); } } /** * Avoid code duplication in {@link #processValue(Object, ConfigDescriptionParameter)} method. * * @param type the {@link Type} of a parameter that should be checked. * @param configValue the value of a parameter that should be checked. * @return true if the type and value matching or false in the opposite. */ private boolean checkType(Type type, Object configValue) { switch (type) { case TEXT: return configValue instanceof String; case BOOLEAN: return configValue instanceof Boolean; case INTEGER: return configValue instanceof BigDecimal || configValue instanceof Integer || configValue instanceof Double && ((Double) configValue).intValue() == (Double) configValue; case DECIMAL: return configValue instanceof BigDecimal || configValue instanceof Double; } return false; } /** * This method serves to replace module configuration references with the {@link Rule}s configuration values. * * @param modules the {@link Rule}'s modules, whose configuration values should be resolved. * @param ruleConfiguration the {@link Rule}'s configuration values that should be resolve module configuration * values. */ private void resolveModuleConfigReferences(List modules, Map ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } } @Override public void added(RuleTemplate element) { String templateUID = element.getUID(); Set rules = new HashSet(); synchronized (this) { Set rulesForResolving = mapTemplateToRules.get(templateUID); if (rulesForResolving != null) { rules.addAll(rulesForResolving); } } for (String rUID : rules) { try { Rule unresolvedRule = get(rUID); Rule resolvedRule = resolveRuleByTemplate(unresolvedRule); Provider provider = getProvider(rUID); if (provider instanceof ManagedRuleProvider) { update(resolvedRule); } else { updated(provider, unresolvedRule, unresolvedRule); } } catch (IllegalArgumentException e) { logger.error("Resolving the rule '{}' by template '{}' failed", rUID, templateUID, e); } } } @Override public void removed(RuleTemplate element) { // Do nothing - resolved rules are independent from templates } @Override public void updated(RuleTemplate oldElement, RuleTemplate element) { // Do nothing - resolved rules are independent from templates } /** * Getter for {@link #scheduleReinitializationDelay} used by {@link RuleEngineImpl} to schedule rule's * re-initialization * tries. * * @return the {@link #scheduleReinitializationDelay}. */ long getScheduleReinitializationDelay() { return scheduleReinitializationDelay; } }
blob data class, long method t t f data class, long method blob 0 14828 https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.core/src/main/java/org/eclipse/smarthome/automation/core/internal/RuleRegistryImpl.java/#L103-L692 1 5298 14828
3570   YES I found bad smells The bad smells are: 1. Duplicate code 2. Long class 3. Data class 4. Large class 5. Data clumps I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } }
blob  Duplicate code2 Long class3 Data class4 Large class5 Data clumps t f f . Duplicate code2. Long class3. Data class4. Large class5. Data clumps blob 0 7852 https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 2 3570 7852
1782 { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } }
blob blob, data class, long method t t t  data class, long method   0 11964 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 1 1782 11964
810  {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; }
blob data class t t f data class blob 0 7648 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 1 810 7648
186 { "output": "YES I found bad smells.\nthe bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. *   * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 2119 https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 1 186 2119
17 { "result": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DimsDataList implements Serializable { /** * */ private static final long serialVersionUID = -5902704017223885965L; private List dimsData; private boolean expression; public DimsDataList() { } public DimsDataList(List chunk) { dimsData = chunk; } public DimsDataList(int[] dataShape) throws Exception { try { // For now we just assume the first dimensions are the slow ones to make an axis out // of. Later read the axis from the meta list but we do not have examples of this so // far. int xaxis=-1,yaxis=-1; for (int i = 0; i=0; i--) { if (dataShape[i]>1) { if (yaxis<0) { getDimsData(i).setPlotAxis(AxisType.Y); yaxis = i; continue; } else if (xaxis<0) { getDimsData(i).setPlotAxis(AxisType.X); xaxis = i; continue; } } } // If we only found a y it may be a multiple-dimension set with only 1D possible. // In that case change y to x. if (yaxis>-1 && xaxis<0) { getDimsData(yaxis).setPlotAxis(AxisType.X); } } finally { //file.close(); } } public Iterable iterable() { return dimsData; } public void add(DimsData dimension) { if (dimsData==null) dimsData = new ArrayList(3); if (dimsData.size()>dimension.getDimension() && dimension.getDimension()>-1) { dimsData.set(dimension.getDimension(), dimension); } else { dimsData.add(dimension); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dimsData == null) ? 0 : dimsData.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DimsDataList other = (DimsDataList) obj; if (dimsData == null) { if (other.dimsData != null) return false; } else if (!dimsData.equals(other.dimsData)) return false; return true; } public static Object[] getDefault() { return new DimsData[]{new DimsData(0)}; } public Object[] getElements() { if (dimsData==null) return null; return dimsData.toArray(new DimsData[dimsData.size()]); } public int size() { if (dimsData==null) return 0; return dimsData.size(); } public DimsData getDimsData(int i) { if (dimsData==null) return null; return dimsData.get(i); } public Iterator iterator() { if (dimsData==null) return null; return dimsData.iterator(); } public void clear() { if (dimsData!=null) dimsData.clear(); } public String toString() { return toString(null); } public String toString(int[] shape) { final StringBuilder buf = new StringBuilder(); buf.append("[ "); int index = 0; for (DimsData d : dimsData) { final int upper = shape!=null ? shape[index] : -1; buf.append(d.getUserString(upper)); if (d!=dimsData.get(dimsData.size()-1)) buf.append(", "); ++index; } buf.append(" ]"); return buf.toString(); } public boolean isRangeDefined() { for (DimsData data : iterable()) { if (data.getSliceRange()!=null) return true; } return false; } public int getAxisCount() { if (dimsData==null) return -1; int count = 0; for (DimsData dd : dimsData) { if (!dd.getPlotAxis().hasValue()) count++; } return count; } public int getRangeCount() { int count = 0; for (DimsData dd : dimsData) { if (dd.getPlotAxis()==AxisType.RANGE) count++; } return count; } public boolean is2D() { return getAxisCount()==2; } public DimsDataList clone() { final DimsDataList clone = new DimsDataList(); for (DimsData dd : iterable()) { DimsData dnew = dd.clone(); clone.add(dnew); } clone.expression = expression; return clone; } /** * Sets any axes there are to the axis passed in */ public void normalise(AxisType axis) { for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) dd.setPlotAxis(axis); } } /** * Probably not best algorithm but we are dealing with very small arrays here. * This is simply trying to ensure that only one dimension is selected as an * axis because the plot has changed. * * @param iaxisToFind */ public void setSingleAxisOnly(AxisType iaxisToFind, AxisType iaxisValue) { DimsData found = null; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==iaxisToFind) { dd.setPlotAxis(iaxisValue); found=dd; } } if (found!=null) { for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is x for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue()) { dd.setPlotAxis(iaxisValue); found=dd; } } for (DimsData dd : iterable()) { if (dd==found) continue; dd.setPlotAxis(AxisType.SLICE); } } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis */ public void setTwoAxesOnly(AxisType firstAxis, AxisType secondAxis) { boolean foundFirst = false, foundSecond = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; } if (foundFirst&&foundSecond) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } /** * Bit of a complex method. It simply tries to leave the data with * two axes selected by finding the most likely two dimensions that * should be plot axes. * * @param firstAxis * @param secondAxis * @param thirdAxis */ public void setThreeAxesOnly(AxisType firstAxis, AxisType secondAxis, AxisType thirdAxis) { boolean foundFirst = false, foundSecond = false, foundThird = false; for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) foundFirst = true; if (dd.getPlotAxis()==secondAxis) foundSecond = true; if (dd.getPlotAxis()==thirdAxis) foundThird = true; } if (foundFirst&&foundSecond&&foundThird) { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } else { // We have to decide which of the others is first and second if (!foundFirst) foundFirst = processAxis(firstAxis, secondAxis, thirdAxis); if (!foundSecond) foundSecond = processAxis(secondAxis, firstAxis, thirdAxis); if (!foundThird) foundThird = processAxis(thirdAxis, firstAxis, secondAxis); for (DimsData dd : iterable()) { if (dd.getPlotAxis()==firstAxis) continue; if (dd.getPlotAxis()==secondAxis) continue; if (dd.getPlotAxis()==thirdAxis) continue; if (dd.getPlotAxis()==AxisType.RANGE) continue; dd.setPlotAxis(AxisType.SLICE); } return; } } private final boolean processAxis(AxisType axis, AxisType... ignoredAxes) { final List ignored = asList(ignoredAxes); for (DimsData dd : iterable()) { if (!dd.getPlotAxis().hasValue() && !ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } for (DimsData dd : iterable()) { if (!ignored.contains(dd.getPlotAxis())) { dd.setPlotAxis(axis); return true; } } return false; } /** * Convert a primitive array to a list. * @param array - an array of primitives * @return */ @SuppressWarnings("unchecked") private static final List asList(final Object array) { if (!array.getClass().isArray()) throw new IllegalArgumentException("Not an array"); return new AbstractList() { @Override public T get(int index) { return (T) Array.get(array, index); } @Override public int size() { return Array.getLength(array); } }; } public boolean isXFirst() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().hasValue()) continue; return dd.getPlotAxis()==AxisType.X; } return false; } public void reverseImage() { for (DimsData dd : iterable()) { if (dd.getPlotAxis()==AxisType.X) { dd.setPlotAxis(AxisType.Y); continue; } if (dd.getPlotAxis()==AxisType.Y) { dd.setPlotAxis(AxisType.X); continue; } } } public boolean isExpression() { return expression; } public void setExpression(boolean expression) { this.expression = expression; } public boolean isEmpty() { return dimsData==null || dimsData.isEmpty(); } public boolean isAdvanced() { for (DimsData dd : iterable()) { if (dd.getPlotAxis().isAdvanced()) return true; } return false; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public List getDimsData() { return dimsData; } /** * DO NOT USE THIS IS FOR XML SERLIALIZATION * @return */ public void setDimsData(List dimsData) { this.dimsData = dimsData; } public void removeLargeStacks(ISliceSystem slicingSystem, int maxStack) { for (DimsData dd : getDimsData()) { if (dd.getPlotAxis().isStack(slicingSystem)) { if (dd.getSliceRange(true)==null || "".equals(dd.getSliceRange(true)) || "all".equals(dd.getSliceRange(true))) { final ILazyDataset lz = slicingSystem.getData().getLazySet(); if (lz!=null) { final int size = lz.getShape()[dd.getDimension()]; if (size>=maxStack) { // We set a default slice dd.setSliceRange("0:25"); } } } } } } public Slice[] toSliceArray(int[] dataShape) { final Slice[] ret = new Slice[size()]; for (int i = 0; i < size(); i++) { DimsData dd = getDimsData(i); if (dd.isSlice()) { ret[i] = new Slice(dd.getSlice(), dd.getSlice()+1); } else { ret[i] = new Slice(dataShape[dd.getDimension()]); } } return ret; } /** * Export to Map from DimsDataList * @return */ public Map toMap() { final Map ret = new HashMap(size()); for (DimsData dd : iterable()) { if (dd.isSlice()) { ret.put(dd.getDimension(), String.valueOf(dd.getSlice())); } else if (dd.isTextRange()) { ret.put(dd.getDimension(), dd.getSliceRange()!=null ? dd.getSliceRange() : "all"); } else if ( dd.getPlotAxis()!=null){ ret.put(dd.getDimension(), dd.getPlotAxis().getName()); } } return ret; } /** * Set the current DimsDataList to what is defined in the pass in map. * @param map * @param shape */ public void fromMap(Map map, int[] shape) { clear(); for (int i = 0; i < shape.length; i++) { add(new DimsData(i)); } if (map.isEmpty()) { // Make one up getDimsData(0).setSliceRange("all"); if (size()==2) { getDimsData(1).setPlotAxis(AxisType.X); } else if (size()>2) { getDimsData(1).setPlotAxis(AxisType.Y); getDimsData(2).setPlotAxis(AxisType.X); for (int i = 3; i < size(); i++) { getDimsData(i).setSlice(0); } } } else { // Init one from map saved int dim = 0; for (DimsData dd : iterable()) { String value = map.get(dd.getDimension()); if (value==null) value = map.get(String.valueOf(dd.getDimension())); if (value!=null) { if ("all".equals(value)) { dd.setPlotAxis(AxisType.RANGE); continue; } AxisType at = AxisType.forLabel(value); if (at!=null) { dd.setPlotAxis(at); continue; } try { dd.setSlice(Integer.parseInt(value)); } catch (Exception ne) { dd.setSliceRange(value); } } else { AxisType type = AxisType.forAxis(dim); dd.setPlotAxis(type); ++dim; } } } } }
blob long method, data class t t f long method, data class blob 0 652 https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.slicing.api/src/org/eclipse/dawnsci/slicing/api/system/DimsDataList.java/#L26-L549 1 17 652
2022  1. Long method 2. Data class 3. Large class 4. Primitive obsession 5. Duplicated code 6. Feature envy 7. Inconsistent naming convention 8. Inappropriate comment I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public abstract class AbstractOAuth2ApiBinding implements ApiBinding, InitializingBean { private final String accessToken; private RestTemplate restTemplate; /** * Constructs the API template without user authorization. This is useful for accessing operations on a provider's API that do not require user authorization. */ protected AbstractOAuth2ApiBinding() { accessToken = null; restTemplate = createRestTemplateWithCulledMessageConverters(); configureRestTemplate(restTemplate); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token */ protected AbstractOAuth2ApiBinding(String accessToken) { this(accessToken, TokenStrategy.AUTHORIZATION_HEADER); } /** * Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user. * @param accessToken the access token * @param tokenStrategy Specifies how access tokens are sent on API requests. Defaults to sending them in Authorization header. */ protected AbstractOAuth2ApiBinding(String accessToken, TokenStrategy tokenStrategy) { this.accessToken = accessToken; restTemplate = createRestTemplate(accessToken, getOAuth2Version(), tokenStrategy); configureRestTemplate(restTemplate); } /** * Set the ClientHttpRequestFactory. This is useful when custom configuration of the request factory is required, such as configuring custom SSL details. * @param requestFactory the request factory */ public void setRequestFactory(ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); } // implementing ApiBinding public boolean isAuthorized() { return accessToken != null; } // public implementation operations /** * Obtains a reference to the REST client backing this API binding and used to perform API calls. * Callers may use the RestTemplate to invoke other API operations not yet modeled by the binding interface. * Callers may also modify the configuration of the RestTemplate to support unit testing the API binding with a mock server in a test environment. * During construction, subclasses may apply customizations to the RestTemplate needed to invoke a specific API. * @see RestTemplate#setMessageConverters(java.util.List) * @see RestTemplate#setErrorHandler(org.springframework.web.client.ResponseErrorHandler) * @return a reference to the {@link RestTemplate} that backs this API binding. */ public RestTemplate getRestTemplate() { return restTemplate; } // subclassing hooks /** * Returns the version of OAuth2 the API implements. * By default, returns {@link OAuth2Version#BEARER} indicating versions of OAuth2 that apply the bearer token scheme. * Subclasses may override to return another version. * @see OAuth2Version * @return the version of OAuth 2 in play. */ protected OAuth2Version getOAuth2Version() { return OAuth2Version.BEARER; } /** * Subclassing hook to enable customization of the RestTemplate used to consume provider API resources. * An example use case might be to configure a custom error handler. * Note that this method is called after the RestTemplate has been configured with the message converters returned from getMessageConverters(). * @param restTemplate the RestTemplate to configure. */ protected void configureRestTemplate(RestTemplate restTemplate) { } /** * Returns a list of {@link HttpMessageConverter}s to be used by the internal {@link RestTemplate}. * By default, this includes a {@link StringHttpMessageConverter}, a {@link MappingJackson2HttpMessageConverter}, a {@link ByteArrayHttpMessageConverter}, and a {@link FormHttpMessageConverter}. * The {@link FormHttpMessageConverter} is set to use "UTF-8" character encoding. * Override this method to add additional message converters or to replace the default list of message converters. * @return a list of message converters to be used by RestTemplate */ protected List> getMessageConverters() { List> messageConverters = new ArrayList>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(getFormMessageConverter()); messageConverters.add(getJsonMessageConverter()); messageConverters.add(getByteArrayMessageConverter()); return messageConverters; } /** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List> partConverters = new ArrayList>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; } /** * Returns a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. * Override to customize the message converter (for example, to set a custom object mapper or supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link MappingJackson2HttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { return new MappingJackson2HttpMessageConverter(); } /** * Returns a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. * By default, the message converter supports "image/jpeg", "image/gif", and "image/png" media types. * Override to customize the message converter (for example, to set supported media types). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return a {@link ByteArrayHttpMessageConverter} to be used by the internal {@link RestTemplate} when consuming image or other binary resources. */ protected ByteArrayHttpMessageConverter getByteArrayMessageConverter() { ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_GIF, MediaType.IMAGE_PNG)); return converter; } private RestTemplate createRestTemplate(String accessToken, OAuth2Version version, TokenStrategy tokenStrategy) { RestTemplate client = createRestTemplateWithCulledMessageConverters(); ClientHttpRequestInterceptor interceptor = tokenStrategy.interceptor(accessToken, version); List interceptors = new LinkedList(); interceptors.add(interceptor); client.setInterceptors(interceptors); return client; } // Temporary: The RestTemplate that accepts a list of message converters wasn't added until Spring 3.2.7. // Remove this method and use that constructor exclusively when 3.1.x support is no longer necessary (Spring Social 2.0). private RestTemplate createRestTemplateWithCulledMessageConverters() { RestTemplate client; List> messageConverters = getMessageConverters(); try { client = new RestTemplate(messageConverters); } catch (NoSuchMethodError e) { client = new RestTemplate(); client.setMessageConverters(messageConverters); } client.setRequestFactory(ClientHttpRequestFactorySelector.getRequestFactory()); return client; } /** * After construction, include option to decorate the {@link RestTemplate} followed by an optional * configuration step. Many providers initialize sub-APIs, and this provides a convenient hook. * @throws Exception if any error occurs decorating the RestTemplate */ @Override public void afterPropertiesSet() throws Exception { this.restTemplate = postProcess(this.restTemplate); postConstructionConfiguration(); } /** * Extensible hook to decorate {@link RestTemplate} or wrap it with a proxy of any type. By default, it just passes it through with no changes. * * @param restTemplate the RestTemplate to decorate * @return the decorated RestTemplate */ protected RestTemplate postProcess(RestTemplate restTemplate) { return restTemplate; } /** * An extension point to perform key initialization after everything is configured. Existing providers * are encouraged to migrate any form of constructor-based initialization into this method. * * NOTE: To not break backwards compatibility, this method defaults to doing nothing. */ protected void postConstructionConfiguration() { } }
blob  Long method2 Data class3 Large class4 Primitive obsession5 Duplicated code6 Feature envy7 Inconsistent naming convention8 Inappropriate comment f f f . Long method2. Data class3. Large class4. Primitive obsession5. Duplicated code6. Feature envy7. Inconsistent naming convention8. Inappropriate comment blob 0 12792 https://github.com/spring-projects/spring-social/blob/b2715375f0ee98cda5e2e29728e51943822f938c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java/#L43-L242 2 2022 12792
1966     { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); }
blob data class t t f data class blob 0 12599 https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 1 1966 12599
504 {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; private Long libvirtVersion; @Override public void configure(Map params) throws ConfigurationException { super.configure(params); getPifs(); // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } bridgeNameSchema = (String)params.get("network.bridge.name.schema"); String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh"); if (_modifyVxlanPath == null) { throw new ConfigurationException("Unable to find modifyvxlan.sh"); } libvirtVersion = (Long) params.get("libvirtVersion"); if (libvirtVersion == null) { libvirtVersion = 0L; } } public void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List bridges = new ArrayList(); for (File netdev : netdevs) { final File isbridge = new File(netdev.getAbsolutePath() + "/bridge"); final String netdevName = netdev.getName(); s_logger.debug("looking in file " + netdev.getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } String guestBridgeName = _libvirtComputingResource.getGuestBridgeName(); String publicBridgeName = _libvirtComputingResource.getPublicBridgeName(); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (_libvirtComputingResource.isPublicBridge(bridge)) { _pifs.put("public", pif); } if (guestBridgeName != null && bridge.equals(guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + guestBridgeName + "' found as a physical device"); _pifs.put("private", guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + publicBridgeName + "' found as a physical device"); _pifs.put("public", publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (File anInterface : interfaces) { final String fname = anInterface.getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (LibvirtComputingResource.isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } protected boolean isBroadcastTypeVlanOrVxlan(final NicTO nic) { return nic != null && (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan); } protected boolean isValidProtocolAndVnetId(final String vNetId, final String protocol) { return vNetId != null && protocol != null && !vNetId.equalsIgnoreCase("untagged"); } @Override public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType, String nicAdapter, Map extraConfig) throws InternalErrorException, LibvirtException { if (s_logger.isDebugEnabled()) { s_logger.debug("nic=" + nic); if (nicAdapter != null && !nicAdapter.isEmpty()) { s_logger.debug("custom nic adapter=" + nicAdapter); } } LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); String vNetId = null; String protocol = null; if (isBroadcastTypeVlanOrVxlan(nic)) { vNetId = Networks.BroadcastDomainType.getValue(nic.getBroadcastUri()); protocol = Networks.BroadcastDomainType.getSchemeValue(nic.getBroadcastUri()).scheme(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); Integer networkRateKBps = 0; if (libvirtVersion > ((10 * 1000 + 10))) { networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; } if (nic.getType() == Networks.TrafficType.Guest) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "private", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { String brname = ""; if (trafficLabel != null && !trafficLabel.isEmpty()) { brname = trafficLabel; } else { brname = _bridges.get("guest"); } intf.defBridgeNet(brname, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Control) { /* Make sure the network is still there */ createControlNetwork(); intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Public) { if (isBroadcastTypeVlanOrVxlan(nic) && isValidProtocolAndVnetId(vNetId, protocol)) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } else { String brName = createVnetBr(vNetId, "public", protocol); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter), networkRateKBps); } } else if (nic.getType() == Networks.TrafficType.Management) { intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } else if (nic.getType() == Networks.TrafficType.Storage) { String storageBrName = nic.getName() == null ? _bridges.get("private") : nic.getName(); intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType, nicAdapter)); } if (nic.getPxeDisable()) { intf.setPxeDisable(true); } return intf; } @Override public void unplug(LibvirtVMDef.InterfaceDef iface) { deleteVnetBr(iface.getBrName()); } @Override public void attach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("brctl addif " + iface.getBrName() + " " + iface.getDevName()); } @Override public void detach(LibvirtVMDef.InterfaceDef iface) { Script.runSimpleBashScript("test -d /sys/class/net/" + iface.getBrName() + "/brif/" + iface.getDevName() + " && brctl delif " + iface.getBrName() + " " + iface.getDevName()); } private String generateVnetBrName(String pifName, String vnetId) { return "br" + pifName + "-" + vnetId; } private String generateVxnetBrName(String pifName, String vnetId) { return "brvx-" + vnetId; } private String createVnetBr(String vNetId, String pifKey, String protocol) throws InternalErrorException { String nic = _pifs.get(pifKey); if (nic == null) { // if not found in bridge map, maybe traffic label refers to pif already? File pif = new File("/sys/class/net/" + pifKey); if (pif.isDirectory()) { nic = pifKey; } } String brName = ""; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { brName = generateVxnetBrName(nic, vNetId); } else { brName = generateVnetBrName(nic, vNetId); } createVnet(vNetId, nic, brName, protocol); return brName; } private void createVnet(String vnetId, String pif, String brName, String protocol) throws InternalErrorException { synchronized (_vnetBridgeMonitor) { String script = _modifyVlanPath; if (protocol.equals(Networks.BroadcastDomainType.Vxlan.scheme())) { script = _modifyVxlanPath; } final Script command = new Script(script, _timeout, s_logger); command.add("-v", vnetId); command.add("-p", pif); command.add("-b", brName); command.add("-o", "add"); final String result = command.execute(); if (result != null) { throw new InternalErrorException("Failed to create vnet " + vnetId + ": " + result); } } } private void deleteVnetBr(String brName) { synchronized (_vnetBridgeMonitor) { String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName); if (cmdout == null) // Bridge does not exist return; cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '"); if (cmdout != null && cmdout.contains("vnet")) { // Active VM remains on that bridge return; } Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$"); Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$"); Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName); Matcher brNameMatcher = brNameRegex.matcher(brName); String pName = null; String vNetId = null; if (oldStyleBrNameMatcher.find()) { // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far. pName = "undefined"; vNetId = oldStyleBrNameMatcher.group(1); } else if (brNameMatcher.find()) { if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) { pName = brNameMatcher.group(1); } else { pName = "undefined"; } vNetId = brNameMatcher.group(2); } if (vNetId == null || vNetId.isEmpty()) { s_logger.debug("unable to get a vNet ID from name " + brName); return; } String scriptPath = null; if (cmdout != null && cmdout.contains("vxlan")) { scriptPath = _modifyVxlanPath; } else { scriptPath = _modifyVlanPath; } final Script command = new Script(scriptPath, _timeout, s_logger); command.add("-o", "delete"); command.add("-v", vNetId); command.add("-p", pName); command.add("-b", brName); final String result = command.execute(); if (result != null) { s_logger.debug("Delete bridge " + brName + " failed: " + result); } } } private void deleteExistingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = command.execute(parser); boolean foundLinkLocalBr = false; if (result == null && parser.getLines() != null) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String[] tokens = line.split(" "); if (tokens != null && tokens.length < 2) { continue; } final String device = tokens[2]; if (!Strings.isNullOrEmpty(device) && !device.equalsIgnoreCase(linkLocalBr)) { Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR() + " dev " + tokens[2]); } else { foundLinkLocalBr = true; } } } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ip address add 169.254.0.1/16 dev " + linkLocalBr + ";" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } private void createControlNetwork() { createControlNetwork(_bridges.get("linklocal")); } @Override public void createControlNetwork(String privBrName) { deleteExistingLinkLocalRouteTable(privBrName); if (!isExistingBridge(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ip link set " + privBrName + " up; ip address add 169.254.0.1/16 dev " + privBrName, _timeout); } } @Override public boolean isExistingBridge(String bridgeName) { File f = new File("/sys/devices/virtual/net/" + bridgeName + "/bridge"); if (f.exists()) { return true; } else { return false; } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 5124 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java/#L44-L433 1 504 5124
21         { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; }
long method long method, data class t t t  data class   0 682 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 1 21 682
2702 {"response": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } }
blob data class, long method t t f data class, long method blob 0 15334 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 1 2702 15334
2695  { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PlanModifierUtil { private static final Logger LOG = LoggerFactory.getLogger(PlanModifierUtil.class); protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException { if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) { return; } HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey(); Project obChild = (Project) topSelparentPair.getValue(); if (obChild.getRowType().getFieldCount() <= resultSchema.size()) { return; } RelDataType rt = obChild.getRowType(); @SuppressWarnings({ "unchecked", "rawtypes" }) Set collationInputRefs = new HashSet( RelCollations.ordinals(obRel.getCollation())); ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder(); for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) { if (collationInputRefs.contains(i)) { RexNode obyExpr = obChild.getChildExps().get(i); if (obyExpr instanceof RexCall) { LOG.debug("Old RexCall : " + obyExpr); obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema); LOG.debug("New RexCall : " + obyExpr); } inputRefToCallMapBldr.put(i, obyExpr); } } ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build(); if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) { LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size())); throw new CalciteSemanticException("Result Schema didn't match Optimized Op Tree Schema"); } if (replaceProject) { // This removes order-by only expressions from the projections. HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild .getChildExps().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames() .subList(0, resultSchema.size())); obRel.replaceInput(0, replacementProjectRel); } obRel.setInputRefToCallMap(inputRefToCallMap); } private static RexCall adjustOBSchema(RexCall obyExpr, Project obChild, List resultSchema) { int a = -1; List operands = new ArrayList<>(); for (int k = 0; k < obyExpr.operands.size(); k++) { RexNode rn = obyExpr.operands.get(k); for (int j = 0; j < resultSchema.size(); j++) { if( obChild.getChildExps().get(j).toString().equals(rn.toString())) { a = j; break; } } if (a != -1) { operands.add(new RexInputRef(a, rn.getType())); } else { if (rn instanceof RexCall) { operands.add(adjustOBSchema((RexCall)rn, obChild, resultSchema)); } else { operands.add(rn); } } a = -1; } return (RexCall) obChild.getCluster().getRexBuilder().makeCall( obyExpr.getType(), obyExpr.getOperator(), operands); } protected static String generateInvalidSchemaMessage(Project topLevelProj, List resultSchema, int fieldsForOB) { String errorDesc = "Result Schema didn't match Calcite Optimized Op Tree; schema: "; for (FieldSchema fs : resultSchema) { errorDesc += "[" + fs.getName() + ":" + fs.getType() + "], "; } errorDesc += " projection fields: "; for (RexNode exp : topLevelProj.getChildExps()) { errorDesc += "[" + exp.toString() + ":" + exp.getType() + "], "; } if (fieldsForOB != 0) { errorDesc += fieldsForOB + " fields removed due to ORDER BY "; } return errorDesc.substring(0, errorDesc.length() - 2); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 15315 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/PlanModifierUtil.java/#L44-L138 1 2695 15315
2482      { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } }
blob long method, data class t t f long method, data class blob 0 14601 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 1 2482 14601
1543   { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); }
long method Long Method, Data Class t f t  Data Class   0 11243 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 1 1543 11243
772  { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class", "Feature Envy" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); }
long method long method, data class, feature envy t t t  data class, feature envy   0 7285 https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 1 772 7285
1373      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); }
long method long method, data class t t t  data class   0 10803 https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 1 1373 10803
687 {"answer": "YES I found bad smells", "bad smells are": "1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } }
blob 1. data class t t f 1. data class blob 0 6633 https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 1 687 6633
283   YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Switch statement 5. Data class I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
private final class SymbolProcessor implements FunctionVisitor, InstructionVisitorAdapter { private final SourceFunction function; private final LinkedList removeFromBlock = new LinkedList<>(); private int blockInstIndex = 0; private DbgValueInstruction lastDbgValue = null; private InstructionBlock currentBlock = null; private SymbolProcessor(SourceFunction function) { this.function = function; } @Override public void visit(InstructionBlock block) { currentBlock = block; lastDbgValue = null; for (blockInstIndex = 0; blockInstIndex < block.getInstructionCount(); blockInstIndex++) { block.getInstruction(blockInstIndex).accept(this); } if (!removeFromBlock.isEmpty()) { for (int i : removeFromBlock) { currentBlock.remove(i); } removeFromBlock.clear(); } } @Override public void visitInstruction(Instruction instruction) { final MDLocation loc = instruction.getDebugLocation(); if (loc != null) { final LLVMSourceLocation scope = cache.buildLocation(loc); if (scope != null) { instruction.setSourceLocation(scope); } } } @Override public void visit(VoidCallInstruction call) { final SymbolImpl callTarget = call.getCallTarget(); if (callTarget instanceof FunctionDeclaration) { switch (((FunctionDeclaration) callTarget).getName()) { case LLVM_DBG_DECLARE_NAME: handleDebugIntrinsic(call, true); return; case LLVM_DBG_ADDR_NAME: // dbg.declare and dbg.addr have the same interface and, for our purposes, // the same semantics handleDebugIntrinsic(call, true); return; case LLVM_DBG_VALUE_NAME: handleDebugIntrinsic(call, false); return; case LLVM_DEBUGTRAP_NAME: visitDebugTrap(call); return; } } visitInstruction(call); } private void visitDebugTrap(VoidCallInstruction call) { final DebugTrapInstruction trap = DebugTrapInstruction.create(call); currentBlock.set(blockInstIndex, trap); visitInstruction(trap); } private SourceVariable getVariable(VoidCallInstruction call, int index) { final SymbolImpl varSymbol = getArg(call, index); if (varSymbol instanceof MetadataSymbol) { final MDBaseNode mdLocal = ((MetadataSymbol) varSymbol).getNode(); final LLVMSourceSymbol symbol = cache.getSourceSymbol(mdLocal, false); return function.getLocal(symbol); } return null; } private void handleDebugIntrinsic(VoidCallInstruction call, boolean isDeclaration) { SymbolImpl value = getArg(call, LLVM_DBG_INTRINSICS_VALUE_ARGINDEX); if (value instanceof MetadataSymbol) { value = MDSymbolExtractor.getSymbol(((MetadataSymbol) value).getNode()); } if (value == null) { // this may happen if llvm optimizations removed a variable value = new NullConstant(MetaType.DEBUG); } else if (value instanceof ValueInstruction) { ((ValueInstruction) value).setSourceVariable(true); } else if (value instanceof FunctionParameter) { ((FunctionParameter) value).setSourceVariable(true); } int mdLocalArgIndex; int mdExprArgIndex; if (isDeclaration) { mdLocalArgIndex = LLVM_DBG_DECLARE_LOCALREF_ARGINDEX; mdExprArgIndex = LLVM_DBG_DECLARE_EXPR_ARGINDEX; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_NEW) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_NEW; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_NEW; } else if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { mdLocalArgIndex = LLVM_DBG_VALUE_LOCALREF_ARGINDEX_OLD; mdExprArgIndex = LLVM_DBG_VALUE_EXPR_ARGINDEX_OLD; } else { return; } final SourceVariable variable = getVariable(call, mdLocalArgIndex); if (variable == null) { // invalid or unsupported debug information // remove upper indices so we do not need to update the later ones removeFromBlock.addFirst(blockInstIndex); return; } final MDExpression expression = getExpression(call, mdExprArgIndex); if (ValueFragment.describesFragment(expression)) { variable.addFragment(ValueFragment.parse(expression)); } else { variable.addFullDefinition(); } if (isDeclaration) { final DbgDeclareInstruction dbgDeclare = new DbgDeclareInstruction(value, variable, expression); variable.addDeclaration(dbgDeclare); currentBlock.set(blockInstIndex, dbgDeclare); } else { long index = 0; if (call.getArgumentCount() == LLVM_DBG_VALUE_LOCALREF_ARGSIZE_OLD) { final SymbolImpl indexSymbol = call.getArgument(LLVM_DBG_VALUE_INDEX_ARGINDEX_OLD); final Long l = LLVMSymbolReadResolver.evaluateLongIntegerConstant(indexSymbol); if (l != null) { index = l; } } final DbgValueInstruction dbgValue = new DbgValueInstruction(value, variable, index, expression); if (dbgValue.equals(lastDbgValue)) { // at higher optimization levels llvm often duplicates the @llvm.dbg.value // intrinsic call, we remove it again to avoid unnecessary runtime overhead removeFromBlock.addFirst(blockInstIndex); } else { variable.addValue(dbgValue); currentBlock.set(blockInstIndex, dbgValue); lastDbgValue = dbgValue; } } } }
blob  Long method2 Feature envy3 Duplicate code4 Switch statement5 Data class t f f . Long method2. Feature envy3. Duplicate code4. Switch statement5. Data class blob 0 3035 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/sulong/projects/com.oracle.truffle.llvm.parser/src/com/oracle/truffle/llvm/parser/metadata/debuginfo/DebugInfoFunctionProcessor.java/#L145-L308 2 283 3035
342 YES I found bad smells: 1. Long method 2. Feature envy 3. Data class violation 4. Primitive obsession I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; }
long method  Long method2 Feature envy3 Data class violation4 Primitive obsession t f t     0 3502 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 2 342 3502
2138  { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment
long method 1. long method, 2. data class t t f  2. data class long method 0 13259 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 1 2138 13259
1852 YES I found bad smells the bad smells: 1. Long method 2. Primitive obsession 3. Feature envy 4. Data class 5. Duplicate code/unnecessary code repetition 6. Type checking using instanceof 7. Inconsistent naming convention for variables 8. Nested if/else statements indicating complex logic 9. Accessing private fields directly rather than through getters/setters 10. Use of raw types instead of generics 11. Lack of encapsulation/data hiding 12. Lack of proper documentation/comments I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } }
blob  Long method2 Primitive obsession3 Feature envy4 Data class5 Duplicate code/unnecessary code repetition6 Type checking using instanceof7 Inconsistent naming convention for variables 8 Nested if/else statements indicating complex logic9 Accessing private fields directly rather than through getters/setters t f f . Long method2. Primitive obsession3. Feature envy4. Data class5. Duplicate code/unnecessary code repetition6. Type checking using instanceof7. Inconsistent naming convention for variables 8. Nested if/else statements indicating complex logic9. Accessing private fields directly rather than through getters/setters blob 0 12191 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 2 1852 12191
801  { "response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Long parameter list", "3. Feature envy", "4. Data class", "5. Message chains", "6. Lazy class", "7. Duplicate code", "8. Comments"] } I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } }
blob 1. long method, 2. long parameter list, 3. feature envy, 4. data class, 5. message chains, 6. lazy class, 7. duplicate code, 8. comments t t f 1. long method, 2. long parameter list, 3. feature envy, 4. data class, 5. message chains, 6. lazy class, 7. duplicate code, 8. comments blob 0 7591 https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 2 801 7591
172 {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } }
blob long method, data class t t f long method, data class blob 0 2039 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 1 172 2039
3883  {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } }
blob data class t t f data class blob 0 10140 https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 1 3883 10140
725  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } }
blob data class t t f data class blob 0 6841 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 1 725 6841
3535 {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JcloudsBlobStoreBasedObjectStore implements PersistenceObjectStore { private static final Logger log = LoggerFactory.getLogger(JcloudsBlobStoreBasedObjectStore.class); private final String containerNameFirstPart; private final String containerSubPath; private String locationSpec; private JcloudsLocation location; private BlobStoreContext context; private ManagementContext mgmt; public JcloudsBlobStoreBasedObjectStore(String locationSpec, String containerName) { this.locationSpec = locationSpec; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; } private String[] splitOnce(String path) { String separator = subPathSeparator(); int index = path.indexOf(separator); if (index<0) return new String[] { path, "" }; return new String[] { path.substring(0, index), path.substring(index+separator.length()) }; } public JcloudsBlobStoreBasedObjectStore(JcloudsLocation location, String containerName) { this.location = location; String[] segments = splitOnce(containerName); this.containerNameFirstPart = segments[0]; this.containerSubPath = segments[1]; getBlobStoreContext(); } public String getSummaryName() { return (locationSpec!=null ? locationSpec : location)+":"+getContainerNameFull(); } public synchronized BlobStoreContext getBlobStoreContext() { if (context==null) { if (location==null) { Preconditions.checkNotNull(locationSpec, "locationSpec required for remote object store when location is null"); Preconditions.checkNotNull(mgmt, "mgmt not injected / object store not prepared"); location = (JcloudsLocation) mgmt.getLocationRegistry().resolve(locationSpec); } String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null"); String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null"); String provider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null"); String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT); context = JcloudsUtil.newBlobstoreContext(provider, endpoint, identity, credential); // TODO do we need to get location from region? can't see the jclouds API. // doesn't matter in some places because it's already in the endpoint // String region = location.getConfig(CloudLocationConfig.CLOUD_REGION_ID); context.getBlobStore().createContainerInLocation(null, getContainerNameFirstPart()); } return context; } @Override public void prepareForMasterUse() { // backups not supported here, that is all which is needed for master use // that's now normally done *prior* to calling in to here for writes // (and we have already thrown in prepareForSharedUse if legacy backups have been specified as required) } public String getContainerName() { return getContainerNameFull(); } protected String getContainerNameFull() { return mergePaths(containerNameFirstPart, containerSubPath); } protected String getContainerNameFirstPart() { return containerNameFirstPart; } protected String getItemInContainerSubPath(String path) { if (Strings.isBlank(containerSubPath)) return path; return mergePaths(containerSubPath, path); } @Override public void createSubPath(String subPath) { // not needed - subpaths are created on demant // (and buggy on softlayer w swift w jclouds 1.7.2: // throws a "not found" if we're creating an empty directory from scratch) // context.getBlobStore().createDirectory(getContainerName(), subPath); } protected void checkPrepared() { if (context==null) throw new IllegalStateException("object store not prepared"); } @Override public StoreObjectAccessor newAccessor(String path) { checkPrepared(); return new JcloudsStoreObjectAccessor(context.getBlobStore(), getContainerNameFirstPart(), getItemInContainerSubPath(path)); } protected String mergePaths(String basePath, String ...subPaths) { StringBuilder result = new StringBuilder(basePath); for (String subPath: subPaths) { if (result.length()>0 && subPath.length()>0) { result.append(subPathSeparator()); result.append(subPath); } } return result.toString(); } protected String subPathSeparator() { // in case some object stores don't allow / for paths return "/"; } @Override public List listContentsWithSubPath(final String parentSubPath) { checkPrepared(); return FluentIterable.from(context.getBlobStore().list(getContainerNameFirstPart(), ListContainerOptions.Builder.inDirectory(getItemInContainerSubPath(parentSubPath)))) .transform(new Function() { @Override public String apply(@javax.annotation.Nullable StorageMetadata input) { String result = input.getName(); result = Strings.removeFromStart(result, containerSubPath); result = Strings.removeFromStart(result, "/"); return result; } }).toList(); } @Override public void close() { if (context!=null) context.close(); } @Override public String toString() { return Objects.toStringHelper(this) .add("blobStoreContext", context) .add("basedir", containerNameFirstPart) .toString(); } @Override public void injectManagementContext(ManagementContext mgmt) { if (this.mgmt!=null && !this.mgmt.equals(mgmt)) throw new IllegalStateException("Cannot change mgmt context of "+this); this.mgmt = mgmt; } @SuppressWarnings("deprecation") @Override public void prepareForSharedUse(@Nullable PersistMode persistMode, HighAvailabilityMode haMode) { if (mgmt==null) throw new NullPointerException("Must inject ManagementContext before preparing "+this); getBlobStoreContext(); if (persistMode==null || persistMode==PersistMode.DISABLED) { log.warn("Should not be using "+this+" when persistMode is "+persistMode); return; } Boolean backups = mgmt.getConfig().getConfig(BrooklynServerConfig.PERSISTENCE_BACKUPS_REQUIRED); if (Boolean.TRUE.equals(backups)) { log.warn("Using legacy backup for "+this+"; functionality will be removed in future versions, in favor of promotion/demotion-specific backups to a configurable backup location."); throw new FatalConfigurationRuntimeException("Backups not supported for object store ("+this+")"); } } @Override public void deleteCompletely() { if (Strings.isBlank(containerSubPath)) getBlobStoreContext().getBlobStore().deleteContainer(containerNameFirstPart); else newAccessor(containerSubPath).delete(); } }
blob long method, data class t t f long method, data class blob 0 7670 https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/locations/jclouds/src/main/java/org/apache/brooklyn/core/mgmt/persist/jclouds/JcloudsBlobStoreBasedObjectStore.java/#L52-L237 1 3535 7670
1456 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static final class OpCopyBlockProto extends com.google.protobuf.GeneratedMessage implements OpCopyBlockProtoOrBuilder { // Use OpCopyBlockProto.newBuilder() to construct. private OpCopyBlockProto(Builder builder) { super(builder); } private OpCopyBlockProto(boolean noInit) {} private static final OpCopyBlockProto defaultInstance; public static OpCopyBlockProto getDefaultInstance() { return defaultInstance; } public OpCopyBlockProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } private int bitField0_; // required .BaseHeaderProto header = 1; public static final int HEADER_FIELD_NUMBER = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { return header_; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { return header_; } private void initFields() { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasHeader()) { memoizedIsInitialized = 0; return false; } if (!getHeader().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, header_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, header_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)) { return super.equals(obj); } org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other = (org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) obj; boolean result = true; result = result && (hasHeader() == other.hasHeader()); if (hasHeader()) { result = result && getHeader() .equals(other.getHeader()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHeader()) { hash = (37 * hash) + HEADER_FIELD_NUMBER; hash = (53 * hash) + getHeader().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.internal_static_OpCopyBlockProto_fieldAccessorTable; } // Construct using org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getHeaderFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDescriptor(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto getDefaultInstanceForType() { return org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto build() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto buildPartial() { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto result = new org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (headerBuilder_ == null) { result.header_ = header_; } else { result.header_ = headerBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto) { return mergeFrom((org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto other) { if (other == org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpCopyBlockProto.getDefaultInstance()) return this; if (other.hasHeader()) { mergeHeader(other.getHeader()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasHeader()) { return false; } if (!getHeader().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder subBuilder = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(); if (hasHeader()) { subBuilder.mergeFrom(getHeader()); } input.readMessage(subBuilder, extensionRegistry); setHeader(subBuilder.buildPartial()); break; } } } } private int bitField0_; // required .BaseHeaderProto header = 1; private org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> headerBuilder_; public boolean hasHeader() { return ((bitField0_ & 0x00000001) == 0x00000001); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto getHeader() { if (headerBuilder_ == null) { return header_; } else { return headerBuilder_.getMessage(); } } public Builder setHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } header_ = value; onChanged(); } else { headerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } public Builder setHeader( org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder builderForValue) { if (headerBuilder_ == null) { header_ = builderForValue.build(); onChanged(); } else { headerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } public Builder mergeHeader(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto value) { if (headerBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && header_ != org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance()) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.newBuilder(header_).mergeFrom(value).buildPartial(); } else { header_ = value; } onChanged(); } else { headerBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } public Builder clearHeader() { if (headerBuilder_ == null) { header_ = org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.getDefaultInstance(); onChanged(); } else { headerBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder getHeaderBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHeaderFieldBuilder().getBuilder(); } public org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder getHeaderOrBuilder() { if (headerBuilder_ != null) { return headerBuilder_.getMessageOrBuilder(); } else { return header_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder> getHeaderFieldBuilder() { if (headerBuilder_ == null) { headerBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProto.Builder, org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BaseHeaderProtoOrBuilder>( header_, getParentForChildren(), isClean()); header_ = null; } return headerBuilder_; } // @@protoc_insertion_point(builder_scope:OpCopyBlockProto) } static { defaultInstance = new OpCopyBlockProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:OpCopyBlockProto) }
blob data class t t f data class blob 0 11010 https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/protocol/proto/DataTransferProtos.java/#L4858-L5321 1 1456 11010
5741   YES I found bad smells the bad smells are: 1. Data Class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } }
long method  Data Class t f f . Data Class long method 0 14081 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 1 5741 14081
1246     { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } }
long method long method, data class t t t  data class   0 10421 https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 1 1246 10421
1096       { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class Builder { /** * @see AddDomainOptions#primaryNameServer */ public static AddDomainOptions primaryNameServer(String primaryNameServer) { return AddDomainOptions.class.cast(new AddDomainOptions().primaryNameServer(primaryNameServer)); } /** * @see AddDomainOptions#responsiblePerson */ public static AddDomainOptions responsiblePerson(String responsiblePerson) { return AddDomainOptions.class.cast(new AddDomainOptions().responsiblePerson(responsiblePerson)); } /** * @see AddDomainOptions#ttl */ public static AddDomainOptions ttl(int ttl) { return AddDomainOptions.class.cast(new AddDomainOptions().ttl(ttl)); } /** * @see AddDomainOptions#refresh */ public static AddDomainOptions refresh(int refresh) { return AddDomainOptions.class.cast(new AddDomainOptions().refresh(refresh)); } /** * @see AddDomainOptions#retry */ public static AddDomainOptions retry(int retry) { return AddDomainOptions.class.cast(new AddDomainOptions().retry(retry)); } /** * @see AddDomainOptions#expire */ public static AddDomainOptions expire(int expire) { return AddDomainOptions.class.cast(new AddDomainOptions().expire(expire)); } /** * @see AddDomainOptions#minimum */ public static AddDomainOptions minimum(int minimum) { return AddDomainOptions.class.cast(new AddDomainOptions().minimum(minimum)); } /** * @see AddDomainOptions#minimalRecords */ public static AddDomainOptions minimalRecords() { return AddDomainOptions.class.cast(new AddDomainOptions().minimalRecords()); } }
blob data class t t f data class blob 0 9783 https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java/#L21-L77 1 1096 9783
1531 {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } }
blob blob, data class, long method t t t  data class, long method   0 11208 https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 1 1531 11208
5249 { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob long method, data class t t f long method, data class blob 0 14679 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 1 5249 14679
5531   YES, I found bad smells the bad smells are: 1. Long method 2. Data class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; }
long method  Long method2 Data class t f t     0 5816 https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 1 5531 5816
1267      { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } }
blob data class t t f data class blob 0 10549 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 1 1267 10549
55 { "input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example {\n private int field1;\n private String field2;\n\n public Example(int field1, String field2) {\n this.field1 = field1;\n this.field2 = field2;\n }\n\n public void doSomething() {\n if (field1 > 10) {\n System.out.println(\"Field1 is greater than 10\");\n } else {\n System.out.println(\"Field1 is not greater than 10\");\n }\n }\n}" }, "output": "YES I found bad smells\nthe bad smells are: 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob yes i found bad smellsthe bad smells are: 2. data class t t f yes i found bad smellsthe bad smells are: 2. data class blob 0 959 https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Page.java/#L25416-L25594 1 55 959
1293  {"message":"YES I found bad smells","bad_smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } }
long method long method, data class t t t  data class   0 10623 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 1 1293 10623
567        { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlRootElement(name = "VisualizationModel") public class VisualizationModel extends Model { // TODO: // These need to be filled in before using this item // They can be set in the setupItemInfo() method private String writerName; private String readerName; private String outputName; // End required variables private String exportString; private IIOService ioService; private IReader reader; private IWriter writer; /** * The Constructor */ public VisualizationModel() { this(null); } /** * The Constructor, takes an IProject reference. * * @param project The project space this Item will be in. */ public VisualizationModel(IProject project) { super(project); } /** * Sets the name, description, and custom action name * for the item. */ @Override protected void setupItemInfo() { setName("Visualization Model"); setDescription("Specify information about Visualization"); writerName = "VisualizationDefaultWriterName"; readerName = "VisualizationDefaultReaderName"; outputName = "VisualizationDefaultOutputName"; exportString = "Export to Visualization input format"; allowedActions.add(0, exportString); } /** * Adds relevant information that specify the ui provided * to the user when they create the Visualization Model Item * in ICE. */ @Override public void setupForm() { form = new Form(); // Get reference to the IOService // This will let us get IReader/IWriters for // our specific Model ioService = getIOService(); } /** * The reviewEntries method is used to ensure that the form is * in an acceptable state before processing the information it * contains. If the form is not ready to process it is advisable * to have this method return FormStatus.InfoError. * * @param preparedForm * the form to validate * @return whether the form was correctly set up */ @Override protected FormStatus reviewEntries(Form preparedForm) { FormStatus retStatus = FormStatus.ReadyToProcess; // Here you can add code that checks the Entries in the Form // after the user clicks Save. If there are any errors in the // Entry values, return FormStatus.InfoError. Otherwise // return FormStatus.ReadyToProcess. return retStatus; } /** * Use this method to process the data that has been * specified in the form. * * @param actionName * a string representation of the action to perform * @return whether the form was processed successfully */ @Override public FormStatus process(String actionName) { FormStatus retStatus = FormStatus.ReadyToProcess; // This action occurs only when the default processing option is chosen // The default processing option is defined in the last line of the // setupItemInfo() method defined above. if (actionName == exportString) { IFile outputFile = project.getFile(outputName); writer = ioService.getWriter(writerName); retStatus = FormStatus.Processing; writer.write(form, outputFile); refreshProjectSpace(); retStatus = FormStatus.Processed; } else { retStatus = super.process(actionName); } return retStatus; } /** * This method is called when loading a new item either via the item * creation button or through importing a file associated with this * item. It is responsible for setting up the form for user interaction. * * @param fileName * the file to load */ @Override public void loadInput(String fileName) { // Read in the file and set up the form IFile inputFile = project.getFile(fileName); reader = ioService.getReader(readerName); form = reader.read(inputFile); form.setName(getName()); form.setDescription(getDescription()); form.setId(getId()); form.setItemID(getId()); } }
blob data class t t f data class blob 0 5724 https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.demo/src/org/eclipse/ice/demo/visualization/model/VisualizationModel.java/#L30-L165 1 567 5724
1663  {"message": "YES I found bad smells","bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } }
blob Data Class, Long Method t f f Data Class, Long Method blob 0 11615 https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 1 1663 11615
104 { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
final class ArrowType extends JSType { private static final long serialVersionUID = 1L; final Node parameters; JSType returnType; // Whether the return type is inferred. final boolean returnTypeInferred; ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType) { this(registry, parameters, returnType, false); } ArrowType(JSTypeRegistry registry, Node parameters, JSType returnType, boolean returnTypeInferred) { super(registry); this.parameters = parameters == null ? registry.createParametersWithVarArgs(getNativeType(UNKNOWN_TYPE)) : parameters; this.returnType = returnType == null ? getNativeType(UNKNOWN_TYPE) : returnType; this.returnTypeInferred = returnTypeInferred; } @Override public boolean isSubtype(JSType that) { return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL); } @Override protected boolean isSubtype(JSType other, ImplCache implicitImplCache, SubtypingMode subtypingMode) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType, implicitImplCache, subtypingMode)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType, implicitImplCache, subtypingMode)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required argument. return thisParam == null || thisParam.isOptionalArg() || thisParam.isVarArgs() || thatParam != null; } /** * @return True if our parameter spec is equal to {@code that}'s parameter * spec. */ boolean hasEqualParameters(ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { Node thisParam = parameters.getFirstChild(); Node otherParam = that.parameters.getFirstChild(); while (thisParam != null && otherParam != null) { JSType thisParamType = thisParam.getJSType(); JSType otherParamType = otherParam.getJSType(); if (thisParamType != null) { // Both parameter lists give a type for this param, it should be equal if (otherParamType != null && !thisParamType.checkEquivalenceHelper(otherParamType, eqMethod, eqCache)) { return false; } } else { if (otherParamType != null) { return false; } } // Check var_args/optionality if (thisParam.isOptionalArg() != otherParam.isOptionalArg()) { return false; } if (thisParam.isVarArgs() != otherParam.isVarArgs()) { return false; } thisParam = thisParam.getNext(); otherParam = otherParam.getNext(); } // One of the parameters is null, so the types are only equal if both // parameter lists are null (they are equal). return thisParam == otherParam; } boolean checkArrowEquivalenceHelper( ArrowType that, EquivalenceMethod eqMethod, EqCache eqCache) { // Please keep this method in sync with the hashCode() method below. if (!returnType.checkEquivalenceHelper( that.returnType, eqMethod, eqCache)) { return false; } return hasEqualParameters(that, eqMethod, eqCache); } @Override int recursionUnsafeHashCode() { int hashCode = Objects.hashCode(returnType); if (parameters != null) { Node param = parameters.getFirstChild(); while (param != null) { hashCode = hashCode * 31 + Objects.hashCode(param.getJSType()); param = param.getNext(); } } return hashCode; } @Override public JSType getLeastSupertype(JSType that) { throw new UnsupportedOperationException(); } @Override public JSType getGreatestSubtype(JSType that) { throw new UnsupportedOperationException(); } @Override public TernaryValue testForEquality(JSType that) { throw new UnsupportedOperationException(); } @Override public T visit(Visitor visitor) { throw new UnsupportedOperationException(); } @Override T visit(RelationshipVisitor visitor, JSType that) { throw new UnsupportedOperationException(); } @Override public BooleanLiteralSet getPossibleToBooleanOutcomes() { return BooleanLiteralSet.TRUE; } @Override JSType resolveInternal(ErrorReporter reporter) { returnType = safeResolve(returnType, reporter); if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { paramNode.setJSType(paramNode.getJSType().resolve(reporter)); } } return this; } boolean hasUnknownParamsOrReturn() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type == null || type.isUnknownType()) { return true; } } } return returnType == null || returnType.isUnknownType(); } @Override StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) { return sb.append("[ArrowType]"); } @Override public boolean hasAnyTemplateTypesInternal() { return returnType.hasAnyTemplateTypes() || hasTemplatedParameterType(); } private boolean hasTemplatedParameterType() { if (parameters != null) { for (Node paramNode = parameters.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) { JSType type = paramNode.getJSType(); if (type != null && type.hasAnyTemplateTypes()) { return true; } } } return false; } }
blob data class t t f data class blob 0 1359 https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/ArrowType.java/#L53-L312 1 104 1359
1063      { "message": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" }, { "2": "Data Class" } ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); }
long method 1: long method, 2: data class t t t  2: data class   0 9551 https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 1 1063 9551
711 { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DefaultCasDocumentProvider extends org.apache.uima.caseditor.editor.CasDocumentProvider { private static final int READ_TIMEOUT = 30000; private Map tsPreferenceStores = new HashMap(); private Map sessionPreferenceStores = new HashMap(); private static TypeSystemDescription createTypeSystemDescription(InputStream in) throws IOException { // Note: // Type System location is not set correctly, // resolving a referenced type system will fail XMLInputSource xmlTypeSystemSource = new XMLInputSource(in, new File("")); XMLParser xmlParser = UIMAFramework.getXMLParser(); TypeSystemDescription typeSystemDesciptor; try { typeSystemDesciptor = (TypeSystemDescription) xmlParser .parse(xmlTypeSystemSource); typeSystemDesciptor.resolveImports(); } catch (InvalidXMLException e) { throw new IOException(e); } return typeSystemDesciptor; } private static CAS createEmptyCAS(TypeSystemDescription typeSystem) { ResourceSpecifierFactory resourceSpecifierFactory = UIMAFramework .getResourceSpecifierFactory(); TypePriorities typePriorities = resourceSpecifierFactory .createTypePriorities(); FsIndexDescription indexDesciptor = new FsIndexDescription_impl(); indexDesciptor.setLabel("TOPIndex"); indexDesciptor.setTypeName("uima.cas.TOP"); indexDesciptor.setKind(FsIndexDescription.KIND_SORTED); CAS cas; try { cas = CasCreationUtils.createCas(typeSystem, typePriorities, new FsIndexDescription[] { indexDesciptor }); } catch (ResourceInitializationException e) { e.printStackTrace(); cas = null; } return cas; } @Override protected ICasDocument createDocument(Object element) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { // Note: We need to do some error handling here, how to report an error to // the user if downloading the CAS fails? CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); // Note: The type system could be cached to avoid downloading it // for every opened CAS, a time stamp can be used to detect // if it has been changed or not. ClientResponse tsResponse = webResource .path("_typesystem") .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); InputStream tsIn = tsResponse.getEntityInputStream(); TypeSystemDescription tsDesc = null; try { tsDesc = createTypeSystemDescription(tsIn); } catch (IOException e) { // Failed to load ts e.printStackTrace(); // TODO: Stop here, and display some kind of // error message to the user } finally { try { tsIn.close(); } catch (IOException e) { } } // create an empty cas .. CAS cas = createEmptyCAS(tsDesc); ClientResponse casResponse; try { casResponse = webResource .path(URLEncoder.encode(casInput.getName(), "UTF-8")) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .get(ClientResponse.class); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Should never fail, UTF-8 encoding is available on every JRE!", e); } InputStream casIn = casResponse.getEntityInputStream(); org.apache.uima.caseditor.editor.ICasDocument doc = null; try { doc = new DocumentUimaImpl(cas, casIn, DocumentFormat.XMI); } // TODO: Catch exception here, and display error message?! finally { try { casIn.close(); } catch (IOException e) { } } return doc; } return null; } @Override protected void doSaveDocument(IProgressMonitor monitor, Object element, ICasDocument document, boolean overwrite) throws CoreException { if (element instanceof CorpusServerCasEditorInput) { CorpusServerCasEditorInput casInput = (CorpusServerCasEditorInput) element; // TODO: What to do if there is already a newer version? // A dialog could ask if it should be overwritten, or not. if (document instanceof DocumentUimaImpl) { DocumentUimaImpl documentImpl = (DocumentUimaImpl) document; ByteArrayOutputStream outStream = new ByteArrayOutputStream(40000); documentImpl.serialize(outStream); Client client = Client.create(); client.setReadTimeout(READ_TIMEOUT); WebResource webResource = client.resource(casInput.getServerUrl()); byte xmiBytes[] = outStream.toByteArray(); String encodedCasId; try { encodedCasId = URLEncoder.encode(casInput.getName(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Severe error, should never happen, UTF-8 encoding is not supported!")); } ClientResponse response = webResource .path(encodedCasId) .accept(MediaType.TEXT_XML) // TODO: How to fix this? Shouldn't accept do it? .header("Content-Type", MediaType.TEXT_XML) .put(ClientResponse.class, xmiBytes); if (response.getStatus() != 204) { throw new CoreException(new Status(Status.ERROR, CorpusServerPlugin.PLUGIN_ID, "Failed to save document, http error code: " + response.getStatus())); } } } // tell everyone that the element changed and is not dirty any longer fireElementDirtyStateChanged(element, false); } private String getTypeSystemId(CorpusServerCasEditorInput input) { return input.getServerUrl(); } @Override public IPreferenceStore getSessionPreferenceStore(Object element) { // lookup one, and if it does not exist create a new one, and put it! IPreferenceStore store = sessionPreferenceStores.get(getTypeSystemId((CorpusServerCasEditorInput) element)); if (store == null) { store = new PreferenceStore(); sessionPreferenceStores.put(getTypeSystemId((CorpusServerCasEditorInput) element), store); } return store; } @Override protected void disposeElementInfo(Object element, ElementInfo info) { } @Override public Composite createTypeSystemSelectorForm(ICasEditor editor, Composite arg1, IStatus arg2) { // Should not be needed, we can always provide a type system, and // if not, we can only show an error message! return null; } @Override public IPreferenceStore getTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore == null) { IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); String tsStoreString = store.getString(getTypeSystemId((CorpusServerCasEditorInput) element)); tsStore = new PreferenceStore(); if (tsStoreString.length() != 0) { InputStream tsStoreIn = new ByteArrayInputStream(tsStoreString.getBytes(Charset.forName("UTF-8"))); try { tsStore.load(tsStoreIn); } catch (IOException e) { e.printStackTrace(); } } tsPreferenceStores.put(element, tsStore); } return tsStore; } @Override public void saveTypeSystemPreferenceStore(Object element) { PreferenceStore tsStore = tsPreferenceStores.get(element); if (tsStore != null) { ByteArrayOutputStream tsStoreBytes = new ByteArrayOutputStream(); try { tsStore.save(tsStoreBytes, ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } IPreferenceStore store = CorpusServerPlugin.getDefault().getPreferenceStore(); store.putValue(getTypeSystemId((CorpusServerCasEditorInput) element), new String(tsStoreBytes.toByteArray(), Charset.forName("UTF-8"))); } } }
blob data class, long method t t f data class, long method blob 0 6777 https://github.com/apache/opennlp-sandbox/blob/37af4c6d42a9affba4f7c9bbc64175768750563f/caseditor-corpus-server-plugin/src/main/java/org/apache/opennlp/corpus_server/caseditor/DefaultCasDocumentProvider.java/#L63-L333 1 711 6777
291 { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class VizObjectTester { /** * This operation checks the VizObject to insure that the id, name and * description getters and setters function properly. */ @Test public void checkProperties() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; // Create the VizObject VizObject testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Check the id, name and description assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * This operation checks the VizObject class to ensure that its copy() and * clone() operations work as specified. */ @Test public void checkCopying() { // Local declarations int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizObject testNC = new VizObject(); // Test to show valid usage of clone // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Run clone operation VizObject cloneNC = (VizObject) testNC.clone(); // Check the id, name and description with clone assertEquals(testNC.getId(), cloneNC.getId()); assertEquals(testNC.getName(), cloneNC.getName()); assertEquals(testNC.getDescription(), cloneNC.getDescription()); // Test to show valid usage of copy // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Create a new instance of VizObject and copy contents VizObject testNC2 = new VizObject(); testNC2.copy(testNC); // Check the id, name and description with copy assertEquals(testNC.getId(), testNC2.getId()); assertEquals(testNC.getName(), testNC2.getName()); assertEquals(testNC.getDescription(), testNC2.getDescription()); // Test to show an invalid use of copy - null args // Local declarations id = 20110901; name = "September 1st 2011"; description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; testNC = new VizObject(); // Set up the id, name and description testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // Attempt the null copy testNC.copy(null); // Check the id, name and description - nothing has changed assertEquals(testNC.getId(), id); assertEquals(testNC.getName(), name); assertEquals(testNC.getDescription(), description); } /** * * This operation checks the ability of the VizObject to persist itself to * XML and to load itself from an XML input stream. * * * @throws IOException * @throws JAXBException * @throws NullPointerException * */ @Test public void checkXMLPersistence() throws NullPointerException, JAXBException, IOException { // TODO Auto-generated method stub /* * The following sets of operations will be used to test the * "read and write" portion of the VizObject. It will demonstrate the * behavior of reading and writing from an * "XML (inputStream and outputStream)" file. It will use an annotated * VizObject to demonstrate basic behavior. */ // Local declarations VizObject testNC = null, testNC2 = null; int id = 20110901; String name = "September 1st 2011"; String description = "The 1st day of the ninth month in the year of " + "our Lord 2011"; VizJAXBHandler xmlHandler = new VizJAXBHandler(); ArrayList classList = new ArrayList(); classList.add(VizObject.class); // Demonstrate a basic "write" to file. Should not fail // Initialize the object and set values. testNC = new VizObject(); testNC.setId(id); testNC.setName(name); testNC.setDescription(description); // persist to an output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); xmlHandler.write(testNC, classList, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); // Convert to inputStream testNC2 = (VizObject) xmlHandler.read(classList, inputStream); // Check that it equals the persisted object assertTrue(testNC.equals(testNC2)); } /** * * This operation checks the VizObject class to insure that its equals() * operation works. * * */ @Test public void checkEquality() { // Create an VizObject VizObject testVizObject = new VizObject(); // Set its data testVizObject.setId(12); testVizObject.setName("ICE VizObject"); testVizObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create another VizObject to assert Equality with the last VizObject equalObject = new VizObject(); // Set its data, equal to testVizObject equalObject.setId(12); equalObject.setName("ICE VizObject"); equalObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Create an VizObject that is not equal to testVizObject VizObject unEqualObject = new VizObject(); // Set its data, not equal to testVizObject unEqualObject.setId(52); unEqualObject.setName("Bill the VizObject"); unEqualObject.setDescription("This is an VizObject to verify that " + "VizObject.equals() returns false for an object that is not " + "equivalent to testVizObject."); // Create a third VizObject to test Transitivity VizObject transitiveObject = new VizObject(); // Set its data, not equal to testVizObject transitiveObject.setId(12); transitiveObject.setName("ICE VizObject"); transitiveObject.setDescription("This is an VizObject that will " + "be used for testing equality with other VizObjects."); // Assert that these two VizObjects are equal assertTrue(testVizObject.equals(equalObject)); // Assert that two unequal objects returns false assertFalse(testVizObject.equals(unEqualObject)); // Check that equals() is Reflexive // x.equals(x) = true assertTrue(testVizObject.equals(testVizObject)); // Check that equals() is Symmetric // x.equals(y) = true iff y.equals(x) = true assertTrue(testVizObject.equals(equalObject) && equalObject.equals(testVizObject)); // Check that equals() is Transitive // x.equals(y) = true, y.equals(z) = true => x.equals(z) = true if (testVizObject.equals(equalObject) && equalObject.equals(transitiveObject)) { assertTrue(testVizObject.equals(transitiveObject)); } else { fail(); } // Check the Consistent nature of equals() assertTrue(testVizObject.equals(equalObject) && testVizObject.equals(equalObject) && testVizObject.equals(equalObject)); assertTrue(!testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject) && !testVizObject.equals(unEqualObject)); // Assert checking equality with null value returns false assertFalse(testVizObject == null); // Assert that two equal objects have the same hashcode assertTrue(testVizObject.equals(equalObject) && testVizObject.hashCode() == equalObject.hashCode()); // Assert that hashcode is consistent assertTrue(testVizObject.hashCode() == testVizObject.hashCode()); // Assert that hashcodes are different for unequal objects assertFalse(testVizObject.hashCode() == unEqualObject.hashCode()); } /** * * This operation tests the VizObject to insure that it can properly * dispatch notifications when it receives an update that changes its state. * * */ @Test public void checkNotifications() { // Setup the listeners TestVizComponentListener firstListener = new TestVizComponentListener(); TestVizComponentListener secondListener = new TestVizComponentListener(); // Setup the iceObject VizObject iceObject = new VizObject(); // Register the listener iceObject.register(firstListener); // Add the second listener iceObject.register(secondListener); // Change the name of the object iceObject.setName("Warren Buffett"); // Check the listeners to make sure they updated assertTrue(firstListener.wasNotified()); assertTrue(secondListener.wasNotified()); // Reset the listeners firstListener.reset(); secondListener.reset(); // Unregister the second listener so that it no longer receives updates iceObject.unregister(secondListener); // Change the id of the object iceObject.setId(899); assertTrue(firstListener.wasNotified()); // Make sure the second listener was not updated assertFalse(secondListener.wasNotified()); // Reset the listener firstListener.reset(); // Change the description of the object iceObject.setDescription("New description"); // Make sure the listener was notified assertTrue(firstListener.wasNotified()); return; } }
blob long method, data class t t f long method, data class blob 0 3076 https://github.com/eclipse/eavp/blob/20c1ce932e95084e386656526d0a2ac4197f786f/org.eclipse.eavp.tests.viz.datastructures/src/org/eclipse/eavp/tests/viz/service/datastructures/VizObject/VizObjectTester.java/#L40-L344 1 291 3076
1503  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } }
feature envy long method, data class t t f long method, data class feature envy 0 11136 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 1 1503 11136
1471  {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BaseScriptEvalUtil { private static Logger logger = Logger.getLogger( BaseScriptEvalUtil.class.getName( ) ); /** * No instance */ protected BaseScriptEvalUtil( ) { } /** * @param exprText * @param value * @return an instance of ExprTextAndValue */ public static ExprTextAndValue newExprInfo( Object value ) { return ExprTextAndValue.newInstance( value ); } /** * Evaluates a conditional expression. A conditional expression comprises of * a Javascript expression, an operator, and up to 2 operands (which are * Javascript expressions themselves). * Both op1 and op2 will be encapsulated to ExprTextAndValue type to show * specific message in case anything goes wrong, they are assumed not to be * null as well. * * The basic rule for comparison: obj will always be considered as the * default data type,i.e. obj, op1 and op2 will be formatted to the superset * of obj (or Double if obj is numeric)on the condition they are comparable. * e.g. * obj: Integer=>obj, op1 and op2 will be formatted to Double. * obj: Timestamp=>obj, op1 and op2 will be formatted to Date. * obj: Boolean=>obj and op1 will be formatted to Boolean. * obj: String=>obj, op1 and op2 will remain the same * * @param obj * @param operator * @param Op1 * @param Op2 * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2 ) throws DataException { return evalConditionalExpr( obj, operator, Op1, Op2, null ); } /** * * @param obj * @param operator * @param Op1 * @param Op2 * @param compareHints the hints for comparison * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object Op1, Object Op2, BaseCompareHints compareHints ) throws DataException { return evalConditionalExpr( obj, operator, new Object[]{ Op1, Op2 }, compareHints ); } /** * * @param obj * @param operator * @param ops * @return * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops ) throws DataException { return evalConditionalExpr( obj, operator, ops, null ); } /** * * @param obj * @param operator * @param op1 * @param op2 * @return A Boolean result * @throws DataException */ public static Object evalConditionalExpr( Object obj, int operator, Object[] ops, BaseCompareHints compareHints ) throws DataException { ExprTextAndValue[] opTextAndValue = new ExprTextAndValue[ops.length]; for ( int i = 0; i < ops.length; i++ ) { opTextAndValue[i] = createExprTextAndValueInstance( ops[i] ); } Object resultObject = obj; Object[] resultOp = new Object[ops.length]; for ( int i = 0; i < ops.length; i++ ) { resultOp[i] = opTextAndValue[i].value; if ( operator != IConditionalExpression.OP_IN && operator != IConditionalExpression.OP_NOT_IN ) { if ( opTextAndValue[i].value != null && opTextAndValue[i].value.getClass( ).isArray( )) { //For case multi-value type report parameter is involved in signle-value-required filters //more than 1 values are provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) > 1 ) { throw new DataException( ResourceConstants.BAD_COMPARE_SINGLE_WITH_MULITI, toStringForMultiValues( opTextAndValue[i].value ) ); } //no or only one value is provided for multi-value parameter if ( Array.getLength( opTextAndValue[i].value ) == 0 ) { resultOp[i] = null; } else if ( Array.getLength( opTextAndValue[i].value ) == 1 ) { resultOp[i] = Array.get( opTextAndValue[i].value, 0 ); } opTextAndValue[i].value = resultOp[i]; } } } Object[] obArray = MiscUtil.isComparable( obj, operator, opTextAndValue ); if ( obArray != null ) { resultObject = obArray[0]; for ( int i = 1; i < obArray.length; i++ ) { resultOp[i - 1] = obArray[i]; } } if ( logger.isLoggable( Level.FINER ) ) { String logStr = ""; for ( int i = 0; i < ops.length; i++ ) { logStr += resultOp[i] == null ? null : ( ", resultOp" + i + "=" + BaseLogUtil.toString( resultOp[i] ) ); } logger.entering( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", "evalConditionalExpr() resultObject=" + BaseLogUtil.toString( resultObject ) + ", operator=" + operator + logStr ); } boolean result = false; if ( compareHints != null && IBaseDataSetDesign.NULLS_ORDERING_EXCLUDE_NULLS.equals( compareHints.getNullType( ) ) ) { if ( resultObject == null ) return false; } switch ( operator ) { case IConditionalExpression.OP_EQ : result = compare( resultObject, resultOp[0], compareHints ) == 0; break; case IConditionalExpression.OP_NE : result = compare( resultObject, resultOp[0], compareHints ) != 0; break; case IConditionalExpression.OP_LT : result = compare( resultObject, resultOp[0], compareHints ) < 0; break; case IConditionalExpression.OP_LE : result = compare( resultObject, resultOp[0], compareHints ) <= 0; break; case IConditionalExpression.OP_GE : result = compare( resultObject, resultOp[0], compareHints ) >= 0; break; case IConditionalExpression.OP_GT : result = compare( resultObject, resultOp[0], compareHints ) > 0; break; case IConditionalExpression.OP_BETWEEN : result = between( resultObject, resultOp[0], resultOp[1], compareHints ); break; case IConditionalExpression.OP_NOT_BETWEEN : result = !( between( resultObject, resultOp[0], resultOp[1], compareHints ) ); break; case IConditionalExpression.OP_NULL : result = resultObject == null; break; case IConditionalExpression.OP_NOT_NULL : result = resultObject != null; break; case IConditionalExpression.OP_TRUE : result = isTrueOrFalse( resultObject, Boolean.TRUE ); break; case IConditionalExpression.OP_FALSE : result = isTrueOrFalse( resultObject, Boolean.FALSE ); break; case IConditionalExpression.OP_LIKE : result = like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_LIKE : result = !like( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_TOP_N : case IConditionalExpression.OP_BOTTOM_N : case IConditionalExpression.OP_TOP_PERCENT : case IConditionalExpression.OP_BOTTOM_PERCENT : // Top/Bottom expressions are only available in filters for now; direct evaluation is not supported throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "Top/Bottom(N) outside of row filters" ); /* * case IConditionalExpression.OP_ANY : throw new DataException( * ResourceConstants.UNSUPPORTTED_COND_OPERATOR, "ANY" ); */ case IConditionalExpression.OP_MATCH : result = match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_NOT_MATCH : result = !match( resultObject, resultOp[0] ); break; case IConditionalExpression.OP_IN : result = in( resultObject, resultOp ); break; case IConditionalExpression.OP_NOT_IN : result = !in( resultObject, resultOp ); break; case IConditionalExpression.OP_JOINT : result = joint( resultObject, resultOp[0] ); break; default : throw new DataException( ResourceConstants.UNSUPPORTTED_COND_OPERATOR, Integer.valueOf( operator) ); } logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalConditionalExpr", Boolean.valueOf( result ) ); return Boolean.valueOf( result ); } /** * @param o1 * @return */ private static ExprTextAndValue createExprTextAndValueInstance( Object o ) { ExprTextAndValue op; if(! (o instanceof ExprTextAndValue )) op = ExprTextAndValue.newInstance( o ); else op = (ExprTextAndValue)o; return op; } /** * Compare two value according to given comparator. * @param obj1 * @param obj2 * @param comp * @return * @throws DataException */ public static int compare( Object obj1, Object obj2, BaseCompareHints compareHints ) throws DataException { if ( obj1 == null || obj2 == null ) { return CompareNullValue( obj1, obj2, compareHints ); } try { if ( MiscUtil.isSameType( obj1, obj2 ) ) { if ( obj1 instanceof String ) { if ( compareHints == null ) return ( (String)obj1 ).compareTo( (String)obj2 ); return compareAsString( obj1, obj2, compareHints ); } else if ( obj1 instanceof Boolean ) { if ( obj1.equals( obj2 ) ) return 0; Boolean bool = (Boolean) obj1; if ( bool.equals( Boolean.TRUE ) ) return 1; else return -1; } else if ( obj1 instanceof Comparable ) { return ( (Comparable) obj1 ).compareTo( obj2 ); } else if ( obj1 instanceof Collection ) { Collection o1 = (Collection) obj1; Collection o2 = (Collection) obj2; if ( o1.size( ) != o2.size( ) ) return -1; Iterator it1 = o1.iterator( ); Iterator it2 = o2.iterator( ); while ( it1.hasNext( ) ) { int result = compare( it1.next( ), it2.next( ) ); if ( result != 0 ) return result; } return 0; } // most judgements should end here else { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBigDecimal( obj1 ) || MiscUtil.isBigDecimal( obj2 ) ) { BigDecimal a = DataTypeUtil.toBigDecimal( obj1 ); BigDecimal b = DataTypeUtil.toBigDecimal( obj2 ); return a.compareTo( b ); } else if ( MiscUtil.isNumericOrString( obj1 ) && MiscUtil.isNumericOrString( obj2 ) ) { try { return DataTypeUtil.toDouble( obj1 ) .compareTo( DataTypeUtil.toDouble( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isDateOrString( obj1 ) && MiscUtil.isDateOrString( obj2 ) ) { try { return DataTypeUtil.toDate( obj1 ) .compareTo( DataTypeUtil.toDate( obj2 ) ); } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( MiscUtil.isBooleanOrString( obj1 ) && MiscUtil.isBooleanOrString( obj2 ) ) { try { boolean b1 = DataTypeUtil.toBoolean( obj1 ).booleanValue( ); boolean b2 = DataTypeUtil.toBoolean( obj2 ).booleanValue( ); if ( b1 == b2 ) { return 0; } else if ( b1 == false && b2 == true ) { return -1; } else { return 1; } } catch ( Exception e ) { return compareAsString( obj1, obj2, compareHints ); } } else if ( obj1 instanceof String || obj2 instanceof String ) { return compareAsString( obj1, obj2, compareHints ); } else throw new DataException( ResourceConstants.BAD_COMPARE_EXPR, new Object[]{ obj1, obj2 } ); } catch ( BirtException e ) { throw DataException.wrap( e ); } } private static String toStringForMultiValues( Object o ) { if ( o == null ) { return null; } if ( o.getClass( ).isArray( ) && Array.getLength( o ) > 1 ) { StringBuilder buf = new StringBuilder( ); buf.append(Array.get( o, 0 )); buf.append(", "); buf.append(Array.get( o, 1)); buf.append( "..."); return buf.toString( ); } return o.toString( ); } private static int CompareNullValue( Object obj1, Object obj2, BaseCompareHints compareHints ) { if ( compareHints == null ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { String type = compareHints.getNullType( ); if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_HIGHEST.equals( type ) ) { // all non-null values are less than null value if ( obj1 == null && obj2 != null ) return 1; else if ( obj1 != null && obj2 == null ) return -1; else return 0; } else if ( IBaseDataSetDesign.NULLS_ORDERING_NULLS_LOWEST.equals( type ) ) { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } else { // all non-null values are greater than null value if ( obj1 == null && obj2 != null ) return -1; else if ( obj1 != null && obj2 == null ) return 1; else return 0; } } } private static int compareAsString( Object obj1, Object obj2, BaseCompareHints comp ) throws BirtException { return ( comp == null || comp.getComparator( ) == null ) ? DataTypeUtil.toString( obj1 ) .compareTo( DataTypeUtil.toString( obj2 ) ) : comp.getComparator( ).compare( DataTypeUtil.toString( obj1 ), DataTypeUtil.toString( obj2 ) ); } /** * Most objects should already be formatted to the same type by method * formatToComparable at this point if neither of them is null. This method * will therefore be terminated pretty soon except for calling from method * between with weird parameters like obj:String, op1:Double and op2:Date. * * @param obj1 * @param obj2 * @return -1,0 and 1 standing for <,= and > respectively * @throws DataException */ public static int compare( Object obj1, Object obj2 ) throws DataException { return compare( obj1, obj2, null ); } /** * @param resultObject * @param resultOp1 * @param resultOp2 * @return true if resultObject is between resultOp1 and resultOp2, false * otherwise * @throws DataException */ private static boolean between( Object resultObject, Object resultOp1, Object resultOp2, BaseCompareHints compareHints ) throws DataException { return compare( resultObject, resultOp1, compareHints ) >= 0 && compare( resultObject, resultOp2, compareHints ) <= 0; } /** * @param obj * @param bln * @return true if obj equals to bln, false otherwise */ private static boolean isTrueOrFalse( Object obj, Boolean bln ) { if ( obj == null ) return false; try { return DataTypeUtil.toBoolean( obj ).equals( bln ); } catch ( BirtException e ) { return false; } } // Pattern to determine if a Match operation uses Javascript regexp syntax private static Pattern s_JSReExprPattern; // Gets a matcher to determine if a match pattern string is of JavaScript syntax // The pattern matches string like "/regexpr/gmi", which is used in JavaScript to construct a RegExp object private static Matcher getJSReExprPatternMatcher( String patternStr ) { if ( s_JSReExprPattern == null ) s_JSReExprPattern = Pattern.compile("^/(.*)/([a-zA-Z]*)$"); return s_JSReExprPattern.matcher( patternStr ); } private static boolean match( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // Pattern can be one of the following: // (1)Java regular expression pattern // (2)JavaScript RegExp construction syntax: "/RegExpr/[flags]", where flags // can be a combination of 'g', 'm', 'i' Matcher jsReExprMatcher = getJSReExprPatternMatcher( patternStr ); int flags = 0; if ( jsReExprMatcher.matches() ) { // This is a Javascript syntax // Get the flags; we only expect "m", "i", "g" String flagStr = patternStr.substring( jsReExprMatcher.start(2), jsReExprMatcher.end(2) ); for ( int i = 0; i < flagStr.length(); i++) { switch ( flagStr.charAt(i) ) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'g': break; // this flag has no effect default: throw new DataException( ResourceConstants.MATCH_ERROR, patternStr ); } } patternStr = patternStr.substring( jsReExprMatcher.start(1), jsReExprMatcher.end(1) ); } try { Matcher m = Pattern.compile( patternStr, flags ).matcher( sourceStr); return m.find(); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, patternStr ); } } /** * @return true if obj1 matches the given pattern, false otherwise * @throws DataException */ private static boolean like( Object source, Object pattern ) throws DataException { String sourceStr = null; try { sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } String patternStr; try { patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern ); } catch ( BirtException e1 ) { throw new DataException( e1.getLocalizedMessage( ), e1 ); } // As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it // recognizes '_' and '%'. Backslash '\' escapes the next character. // Construct a Java RegExp pattern based on input. We need to translate // unescaped '%' to '.*', and '_' to '.' // Also need to escape any RegExp metacharacter in the source pattern. final String reservedChars = "([{^$|)?*+."; int patternLen = patternStr.length(); StringBuffer buffer = new StringBuffer( patternLen * 2 ); for ( int i = 0; i < patternLen; i++) { char c = patternStr.charAt(i); if ( c == '\\' ) { // Escape char; copy next character to new pattern if // it is '\', '%' or '_' ++i; if ( i < patternLen ) { c = patternStr.charAt( i ); if ( c == '%' || c == '_' ) buffer.append( c ); else if ( c == '\\' ) buffer.append( "\\\\"); // Need to escape \ } else { buffer.append( "\\\\" ); // Leave last \ and escape it } } else if ( c == '%') { buffer.append(".*"); } else if ( c == '_') { buffer.append("."); } else { // Copy this char to target, escape if it is a metacharacter if ( reservedChars.indexOf(c) >= 0 ) { buffer.append('\\'); } buffer.append(c); } } try { String newPatternStr = buffer.toString(); Pattern p = Pattern.compile( newPatternStr ); Matcher m = p.matcher( sourceStr.toString( ) ); return m.matches( ); } catch ( PatternSyntaxException e ) { throw new DataException( ResourceConstants.MATCH_ERROR, e, pattern ); } } /** * * @param resultObj * @return * @throws DataException */ private static boolean in( Object target, Object[] resultObj ) throws DataException { if ( resultObj == null ) return false; for ( int i = 0; i < resultObj.length; i++ ) { if ( compare( target, resultObj[i] ) == 0 ) return true; } return false; } /** * * @param resultObj * @return * @throws DataException */ private static boolean joint( Object target, Object resultObj ) throws DataException { if ( resultObj == null || target == null ) return false; return !java.util.Collections.disjoint( Arrays.asList( target.toString( ) .split( "," )), Arrays.asList( resultObj.toString( ).split( "," ) ) ) ; } /** * Evaluates a IJSExpression or IConditionalExpression * * @param expr * @param cx * @param scope * @param source * @param lineNo * @return * @throws BirtException */ public static Object evalExpr( IBaseExpression expr, ScriptContext cx, String source, int lineNo ) throws DataException { try { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evalExpr", "evalExpr() expr=" + BaseLogUtil.toString( expr ) + ", source=" + source + ", lineNo=" + lineNo ); Object result; if ( expr == null ) { result = null; } else if ( expr instanceof IConditionalExpression ) { // If this is a prepared top(n)/bottom(n) expr, use its // evaluator Object handle = expr.getHandle( ); if ( handle instanceof BaseNEvaluator ) { result = Boolean.valueOf( ( (BaseNEvaluator) handle ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ) ); } else { ConditionalExpression conditionalExpr = (ConditionalExpression) expr; Object expression = evalExpr( conditionalExpr.getExpression( ), cx, source, lineNo ); if ( conditionalExpr.getOperand1( ) instanceof IExpressionCollection ) { IExpressionCollection combinedExpr = (IExpressionCollection) ( (IConditionalExpression) expr ).getOperand1( ); Object[] exprs = combinedExpr.getExpressions( ) .toArray( ); Object[] opValues = new Object[exprs.length]; for ( int i = 0; i < opValues.length; i++ ) { opValues[i] = evalExpr( (IBaseExpression) exprs[i], cx, source, lineNo ); } result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), MiscUtil.flatternMultipleValues( opValues ), null ); } else { Object Op1 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand1( ) ), cx, source, lineNo ); Object Op2 = evalExpr( MiscUtil.constructValidScriptExpression( (IScriptExpression) conditionalExpr.getOperand2( ) ), cx, source, lineNo ); result = evalConditionalExpr( expression, conditionalExpr.getOperator( ), new Object[]{ Op1, Op2 }, null ); } } } else if ( expr instanceof ICollectionConditionalExpression ) { Collection testExpr = ((ICollectionConditionalExpression)expr).getExpr( ); Collection> operand = ((ICollectionConditionalExpression)expr).getOperand( ); List testObj = new ArrayList( ); boolean in = false; for( IScriptExpression se : testExpr ) { testObj.add( evalExpr( se, cx, source, lineNo ) ); } for( Collection op : operand ) { List targetObj = new ArrayList( ); for( IScriptExpression se : op ) { if( se == null ) { targetObj.add( null ); } else { if( se.getHandle( )== null ) { se.setHandle( evalExpr( se, cx, source, lineNo ) ); } targetObj.add( se.getHandle( ) ); } } if( compareIgnoreNull( testObj, targetObj ) == 0 ) { in = Boolean.TRUE; break; } } result = ( ( (ICollectionConditionalExpression) expr ).getOperator( ) == ICollectionConditionalExpression.OP_IN ) ? in : ( !in ); } else { IScriptExpression jsExpr = (IScriptExpression) expr; if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) && jsExpr.getHandle( ) != null ) { result = jsExpr.getHandle( ); } else { if( BaseExpression.constantId.equals( jsExpr.getScriptId( ) ) ) { result = jsExpr.getText( ); jsExpr.setHandle( result ); } else if ( jsExpr.getText( ) != null && jsExpr.getHandle( ) != null ) { if ( jsExpr.getHandle( ) instanceof ICompiledScript ) { result = cx.evaluate( (ICompiledScript) jsExpr.getHandle( ) ); } else { result = ( (BaseCompiledExpression) jsExpr.getHandle( ) ).evaluate( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ) ); } } else { result = evaluateJSAsExpr( cx, ( (IDataScriptEngine) cx.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( cx ), jsExpr.getText( ), source, lineNo ); } } } if ( logger.isLoggable( Level.FINER ) ) logger.exiting( BaseScriptEvalUtil.class.getName( ), "evalExpr", result ); return result; } catch ( BirtException e ) { throw DataException.wrap( e ); } } public static int compareIgnoreNull( List valueList, List targetList ) throws DataException { for( int i = 0; i < valueList.size( ); i++ ) { if( targetList.get( i ) == null ) continue; int result = compare( valueList.get( i ), targetList.get( i ) ); if( result != 0 ) return result; } return 0; } /** * Evaluates a ROM script and converts the result type into one accepted by * BIRT: Double (for all numeric types), java.util.Date, String, Boolean. * Converts Javascript exception and script runtime exceptions to * DataException * * @param cx * @param scope * @param scriptText * @param source * @param lineNo * @return * @throws DataException */ public static Object evaluateJSAsExpr( ScriptContext cx, Scriptable scope, String scriptText, String source, int lineNo) throws DataException { if ( logger.isLoggable( Level.FINER ) ) logger.entering( BaseScriptEvalUtil.class.getName( ), "evaluateJSExpr", "evaluateJSExpr() scriptText=" + scriptText + ", source=" + source + ", lineNo=" + lineNo); Object result; try { result = JavascriptEvalUtil.evaluateScript( Context.getCurrentContext( ), scope, scriptText, source, 0 ); } catch ( BirtException e ) { throw DataException.wrap( e ); } return result; } /** * Wrap the text and value of the operand * */ public static class ExprTextAndValue { Object value; /** * * @param exprText * @param value * @return */ public static ExprTextAndValue newInstance( Object value ) { return new ExprTextAndValue( value ); } /** * * @param exprText * @param value */ public ExprTextAndValue( Object value ) { this.value = value; } } /** * Utility for miscellaneous use * */ private static class MiscUtil { /** * * @param resultExpr * @param resultOp1 * @return */ private static boolean isSameType( Object resultExpr, Object resultOp1 ) { return resultExpr.getClass( ).equals( resultOp1.getClass( ) ); } /** * * @param result * @return */ private static boolean isNumericOrString( Object result ) { return ( result instanceof Number ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBigDecimal( Object result ) { return result instanceof BigDecimal; } /** * * @param result * @return */ private static boolean isDateOrString( Object result ) { return ( result instanceof Date ) || ( result instanceof String ); } /** * * @param result * @return */ private static boolean isBooleanOrString( Object result ) { return ( result instanceof Boolean ) || ( result instanceof String ); } /** * * @param obj * @param operator * @param operands * @return */ private static Object[] isComparable( Object obj, int operator, ExprTextAndValue[] operands ) { if ( needFormat( obj, operator, operands ) ) return formatToComparable( obj, operands ); return null; } /** * * @param obj * @param operator * @param ops * @return */ private static boolean needFormat( Object obj, int operator, ExprTextAndValue[] ops ) { if ( operator < IConditionalExpression.OP_EQ || ( operator > IConditionalExpression.OP_NOT_BETWEEN && operator < IConditionalExpression.OP_IN ) || obj == null || ops.length == 0 || ops[0].value == null ) return false; // op2.value can not be null either if it's a between method else if ( ( operator == IConditionalExpression.OP_BETWEEN || operator == IConditionalExpression.OP_NOT_BETWEEN ) && ops.length < 2 ) return false; return true; } /** * To ease the methods compare and between. Exception with specific * explanation will be thrown if anything goes wrong. * * @param obj * @param operands * @return */ private static Object[] formatToComparable( Object obj, ExprTextAndValue[] operands ) { Object[] obArray = new Object[operands.length + 1]; obArray[0] = obj; for ( int i = 0; i < operands.length; i++ ) { obArray[i + 1] = operands[i].value; } boolean isSameType = true; // obj will always be considered as the default data type // skip if op2.value!=null but is not same type as obj if ( isSameType( obj, obArray[1] ) ) { for ( int i = 1; i < operands.length; i++ ) { if ( obArray[i + 1] != null && !isSameType( obj, obArray[i + 1] ) ) { isSameType = false; break; } } } else { isSameType = false; } if ( isSameType ) return obArray; else if ( obj instanceof Boolean ) populateObArray( obArray[1], obArray ); else populateObArray( obj, obArray ); return obArray; } private static Object[] populateObArray( Object obj, Object[] obArray ) { try { for ( int i = 0; i < obArray.length; i++ ) { if( obArray[i] instanceof Object[] ) return obArray; } if ( obj instanceof Number && !( obj instanceof BigDecimal ) ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDouble( obArray[i] ); } } else if ( obj instanceof java.sql.Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlDate( obArray[i] ); } } else if ( obj instanceof java.sql.Time ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toSqlTime( obArray[i] ); } } else if ( obj instanceof Date ) { for ( int i = 0; i < obArray.length; i++ ) { obArray[i] = DataTypeUtil.toDate( obArray[i] ); } } } catch ( BirtException e ) { // If failed to convert to same date type for comparation, // simply convert them to String. try { makeObjectArrayStringArray( obArray ); } catch ( BirtException e1 ) { //should never reach here. } } // obArray will remain the same if obj is String rather than // Date,Number or Boolean return obArray; } /** * * @param obArray * @throws BirtException */ private static void makeObjectArrayStringArray( Object[] obArray ) throws BirtException { for ( int i = 0; i < obArray.length; i++ ) { if ( obArray[i] != null ) obArray[i] = DataTypeUtil.toString( obArray[i] ); } } /** * @param ise * @return */ private static IScriptExpression constructValidScriptExpression( IScriptExpression ise ) { if( ise != null && BaseExpression.constantId.equals( ise.getScriptId( ) ) ) return ise; return ise != null && ise.getText( ) != null && ise.getText( ).trim( ).length( ) > 0 ? ise : new ScriptExpression( "null" ); } /** * * @return */ private static Object[] flatternMultipleValues( Object[] values ) { if ( values == null || values.length == 0 ) return new Object[0]; List flattern = new ArrayList( ); for ( int i = 0; i < values.length; i++ ) { if ( values[i] instanceof Object[] ) { Object[] flatternObj = (Object[]) values[i]; flattern.addAll( Arrays.asList( flatternMultipleValues( flatternObj ) ) ); } else { flattern.add( values[i] ); } } return flattern.toArray( ); } } }
blob long method, data class t t f long method, data class blob 0 11050 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/script/BaseScriptEvalUtil.java/#L59-L1292 1 1471 11050
2568 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Internal public class BookmarksTables { private static final POILogger logger = POILogFactory .getLogger( BookmarksTables.class ); private PlexOfCps descriptorsFirst = new PlexOfCps( 4 ); private PlexOfCps descriptorsLim = new PlexOfCps( 0 ); private List names = new ArrayList<>(0); public BookmarksTables( byte[] tableStream, FileInformationBlock fib ) { read( tableStream, fib ); } public void afterDelete( int startCp, int length ) { descriptorsFirst.adjust( startCp, -length ); descriptorsLim.adjust( startCp, -length ); for ( int i = 0; i < descriptorsFirst.length(); i++ ) { GenericPropertyNode startNode = descriptorsFirst.getProperty( i ); GenericPropertyNode endNode = descriptorsLim.getProperty( i ); if ( startNode.getStart() == endNode.getStart() ) { logger.log( POILogger.DEBUG, "Removing bookmark #", Integer.valueOf( i ), "..." ); remove( i ); i--; continue; } } } public void afterInsert( int startCp, int length ) { descriptorsFirst.adjust( startCp, length ); descriptorsLim.adjust( startCp - 1, length ); } public int getBookmarksCount() { return descriptorsFirst.length(); } public GenericPropertyNode getDescriptorFirst( int index ) throws IndexOutOfBoundsException { return descriptorsFirst.getProperty( index ); } public int getDescriptorFirstIndex( GenericPropertyNode descriptorFirst ) { // TODO: very non-optimal return Arrays.asList( descriptorsFirst.toPropertiesArray() ).indexOf( descriptorFirst ); } public GenericPropertyNode getDescriptorLim( int index ) throws IndexOutOfBoundsException { return descriptorsLim.getProperty( index ); } public int getDescriptorsFirstCount() { return descriptorsFirst.length(); } public int getDescriptorsLimCount() { return descriptorsLim.length(); } public String getName( int index ) { return names.get( index ); } public int getNamesCount() { return names.size(); } private void read( byte[] tableStream, FileInformationBlock fib ) { int namesStart = fib.getFcSttbfbkmk(); int namesLength = fib.getLcbSttbfbkmk(); if ( namesStart != 0 && namesLength != 0 ) this.names = new ArrayList<>(Arrays.asList(SttbUtils .readSttbfBkmk(tableStream, namesStart))); int firstDescriptorsStart = fib.getFcPlcfbkf(); int firstDescriptorsLength = fib.getLcbPlcfbkf(); if ( firstDescriptorsStart != 0 && firstDescriptorsLength != 0 ) descriptorsFirst = new PlexOfCps( tableStream, firstDescriptorsStart, firstDescriptorsLength, BookmarkFirstDescriptor.getSize() ); int limDescriptorsStart = fib.getFcPlcfbkl(); int limDescriptorsLength = fib.getLcbPlcfbkl(); if ( limDescriptorsStart != 0 && limDescriptorsLength != 0 ) descriptorsLim = new PlexOfCps( tableStream, limDescriptorsStart, limDescriptorsLength, 0 ); } public void remove( int index ) { descriptorsFirst.remove( index ); descriptorsLim.remove( index ); names.remove( index ); } public void setName( int index, String name ) { names.set( index, name ); } public void writePlcfBkmkf( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsFirst == null || descriptorsFirst.length() == 0 ) { fib.setFcPlcfbkf( 0 ); fib.setLcbPlcfbkf( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsFirst.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkf( start ); fib.setLcbPlcfbkf( end - start ); } public void writePlcfBkmkl( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( descriptorsLim == null || descriptorsLim.length() == 0 ) { fib.setFcPlcfbkl( 0 ); fib.setLcbPlcfbkl( 0 ); return; } int start = tableStream.size(); tableStream.write( descriptorsLim.toByteArray() ); int end = tableStream.size(); fib.setFcPlcfbkl( start ); fib.setLcbPlcfbkl( end - start ); } public void writeSttbfBkmk( FileInformationBlock fib, ByteArrayOutputStream tableStream ) throws IOException { if ( names == null || names.isEmpty() ) { fib.setFcSttbfbkmk( 0 ); fib.setLcbSttbfbkmk( 0 ); return; } int start = tableStream.size(); SttbUtils.writeSttbfBkmk( names.toArray( new String[names.size()] ), tableStream ); int end = tableStream.size(); fib.setFcSttbfbkmk( start ); fib.setLcbSttbfbkmk( end - start ); } }
blob long method, data class t t f long method, data class blob 0 14874 https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/BookmarksTables.java/#L29-L204 1 2568 14874
4167  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } }
blob data class, long method t t f data class, long method blob 0 10969 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 1 4167 10969
4153  {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class IndexDataWriter { static final int VERSION = 1; static final int F_INDEXED = 1; static final int F_TOKENIZED = 2; static final int F_STORED = 4; static final int F_COMPRESSED = 8; private final DataOutputStream dos; private final GZIPOutputStream gos; private final BufferedOutputStream bos; private final Set allGroups; private final Set rootGroups; private boolean descriptorWritten; public IndexDataWriter( OutputStream os ) throws IOException { bos = new BufferedOutputStream( os, 1024 * 8 ); gos = new GZIPOutputStream( bos, 1024 * 2 ); dos = new DataOutputStream( gos ); this.allGroups = new HashSet(); this.rootGroups = new HashSet(); this.descriptorWritten = false; } public int write( IndexingContext context, IndexReader indexReader, List docIndexes ) throws IOException { writeHeader( context ); int n = writeDocuments( indexReader, docIndexes ); writeGroupFields(); close(); return n; } public void close() throws IOException { dos.flush(); gos.flush(); gos.finish(); bos.flush(); } public void writeHeader( IndexingContext context ) throws IOException { dos.writeByte( VERSION ); Date timestamp = context.getTimestamp(); dos.writeLong( timestamp == null ? -1 : timestamp.getTime() ); } public void writeGroupFields() throws IOException { { List allGroupsFields = new ArrayList<>( 2 ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS, ArtifactInfo.ALL_GROUPS_VALUE, Store.YES ) ); allGroupsFields.add( new StringField( ArtifactInfo.ALL_GROUPS_LIST, ArtifactInfo.lst2str( allGroups ), Store.YES ) ); writeDocumentFields( allGroupsFields ); } { List rootGroupsFields = new ArrayList<>( 2 ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS, ArtifactInfo.ROOT_GROUPS_VALUE, Store.YES ) ); rootGroupsFields.add( new StringField( ArtifactInfo.ROOT_GROUPS_LIST, ArtifactInfo.lst2str( rootGroups ), Store.YES ) ); writeDocumentFields( rootGroupsFields ); } } public int writeDocuments( IndexReader r, List docIndexes ) throws IOException { int n = 0; Bits liveDocs = MultiFields.getLiveDocs( r ); if ( docIndexes == null ) { for ( int i = 0; i < r.maxDoc(); i++ ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } else { for ( int i : docIndexes ) { if ( liveDocs == null || liveDocs.get( i ) ) { if ( writeDocument( r.document( i ) ) ) { n++; } } } } return n; } public boolean writeDocument( final Document document ) throws IOException { List fields = document.getFields(); List storedFields = new ArrayList<>( fields.size() ); for ( IndexableField field : fields ) { if ( DefaultIndexingContext.FLD_DESCRIPTOR.equals( field.name() ) ) { if ( descriptorWritten ) { return false; } else { descriptorWritten = true; } } if ( ArtifactInfo.ALL_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ALL_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { allGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( ArtifactInfo.ROOT_GROUPS.equals( field.name() ) ) { final String groupList = document.get( ArtifactInfo.ROOT_GROUPS_LIST ); if ( groupList != null && groupList.trim().length() > 0 ) { rootGroups.addAll( ArtifactInfo.str2lst( groupList ) ); } return false; } if ( field.fieldType().stored() ) { storedFields.add( field ); } } writeDocumentFields( storedFields ); return true; } public void writeDocumentFields( List fields ) throws IOException { dos.writeInt( fields.size() ); for ( IndexableField field : fields ) { writeField( field ); } } public void writeField( IndexableField field ) throws IOException { int flags = ( field.fieldType().indexOptions() != IndexOptions.NONE ? F_INDEXED : 0 ) // + ( field.fieldType().tokenized() ? F_TOKENIZED : 0 ) // + ( field.fieldType().stored() ? F_STORED : 0 ); // // + ( false ? F_COMPRESSED : 0 ); // Compressed not supported anymore String name = field.name(); String value = field.stringValue(); dos.write( flags ); dos.writeUTF( name ); writeUTF( value, dos ); } private static void writeUTF( String str, DataOutput out ) throws IOException { int strlen = str.length(); int utflen = 0; int c; // use charAt instead of copying String to char array for ( int i = 0; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen++; } else if ( c > 0x07FF ) { utflen += 3; } else { utflen += 2; } } // TODO optimize storing int value out.writeInt( utflen ); byte[] bytearr = new byte[utflen]; int count = 0; int i = 0; for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( !( ( c >= 0x0001 ) && ( c <= 0x007F ) ) ) { break; } bytearr[count++] = (byte) c; } for ( ; i < strlen; i++ ) { c = str.charAt( i ); if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { bytearr[count++] = (byte) c; } else if ( c > 0x07FF ) { bytearr[count++] = (byte) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } else { bytearr[count++] = (byte) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ); bytearr[count++] = (byte) ( 0x80 | ( ( c >> 0 ) & 0x3F ) ); } } out.write( bytearr, 0, utflen ); } }
blob long method, data class t t f long method, data class blob 0 10936 https://github.com/apache/maven-indexer/blob/8fcb8551345c78871a6adbc0f7238ccd408178d3/indexer-core/src/main/java/org/apache/maven/index/updater/IndexDataWriter.java/#L50-L327 1 4153 10936
875 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class UFile { /* Not sure yet where this should be. */ static { System.loadLibrary("jtux"); } /** Java version of C struct iovec. Click {@link here} for Posix/SUS C API. */ static public class s_iovec { public byte[] iov_base; // base address of data public int iov_len; // size of this piece } /** Java version of C struct statvfs. Click {@link here} for Posix/SUS C API. */ static public class s_statvfs { public long f_bsize; // block size public long f_frsize; // fundamental (fblock) size public long f_blocks; // total number of fblocks public long f_bfree; // number of free fblocks public long f_bavail; // number of avail. fblocks public long f_files; // total number of i-numbers public long f_ffree; // number of free i-numbers public long f_favail; // number of avail. i-numbers public long f_fsid; // file-system ID public long f_flag; // flags (see below) public long f_namemax; // max length of filename } /** Java version of C struct stat. Click {@link here} for Posix/SUS C API. */ static public class s_stat { public long st_dev; // device ID of file system public int st_ino; // i-number public int st_mode; // mode (see below) public int st_nlink; // number of hard links public long st_uid; // user ID public long st_gid; // group ID public long st_rdev; // device ID (if special file) public long st_size; // size in bytes public long st_atime; // last access public long st_mtime; // last data modification public long st_ctime; // last i-node modification public int st_blksize; // optimal I/O size public long st_blocks; // allocated 512-byte blocks } /** Java version of C struct utimbuf. Click {@link here} for Posix/SUS C API. */ static public class s_utimbuf { public long actime; // access time public long modtime; // modification time } /** Java version of fd_set. */ static public class fd_set { static { System.loadLibrary("jtux"); System.out.println("Loaded"); } public byte[] set = new byte[GetSize_fd_set()]; native int GetSize_fd_set(); } /** Java version of C struct pollfd. Click {@link here} for Posix/SUS C API. */ static public class s_pollfd { public int fd; // file descriptor public short events; // input event flags public short revents; // output event flags } /** Calls access. Click {@link here} for Posix/SUS C API. */ public native static void access(String path, int what) throws UErrorException; /** Calls chmod. Click {@link here} for Posix/SUS C API. */ public native static void chmod(String path, int mode) throws UErrorException; /** Calls chown. Click {@link here} for Posix/SUS C API. */ public native static void chown(String path, long uid, long gid) throws UErrorException; /** Calls close. Click {@link here} for Posix/SUS C API. */ public native static void close(int fd) throws UErrorException; /** Does the equivalent of creat, by calling open. Click {@link here} for Posix/SUS C API. */ public static int creat(String path, int perms) throws UErrorException { return open(path, UConstant.O_WRONLY | UConstant.O_CREAT | UConstant.O_TRUNC, perms); } /** Calls dup. Click {@link here} for Posix/SUS C API. */ public native static int dup(int fd) throws UErrorException; /** Calls dup2. Click {@link here} for Posix/SUS C API. */ public native static int dup2(int fd, int fd2) throws UErrorException; /** Calls fchmod. Click {@link here} for Posix/SUS C API. */ public native static void fchmod(int fd, int mode) throws UErrorException; /** Calls fchown. Click {@link here} for Posix/SUS C API. */ public native static void fchown(int fd, long uid, long gid) throws UErrorException; /** Calls fcntl. Click {@link here} for Posix/SUS C API. */ public native static int fcntl(int fd, int op, int arg) throws UErrorException; /** Calls FD_ZERO. Click {@link here} for Posix/SUS C API. */ public native static void FD_ZERO(fd_set set); /** Calls FD_SET. Click {@link here} for Posix/SUS C API. */ public native static void FD_SET(int fd, fd_set set); /** Calls FD_CLR. Click {@link here} for Posix/SUS C API. */ public native static void FD_CLR(int fd, fd_set set); /** Calls FD_ISSET. Click {@link here} for Posix/SUS C API. */ public native static boolean FD_ISSET(int fd, fd_set set); /** Calls fdatasync. Click {@link here} for Posix/SUS C API. */ public native static void fdatasync(int fd) throws UErrorException; /** Calls fstat. Click {@link here} for Posix/SUS C API. */ public native static void fstat(int fd, s_stat buf) throws UErrorException; /** Calls fstatvfs. Click {@link here} for Posix/SUS C API. */ public native static void fstatvfs(int fd, s_statvfs buf) throws UErrorException; /** Calls fsync. Click {@link here} for Posix/SUS C API. */ public native static void fsync(int fd) throws UErrorException; /** Calls ftruncate. Click {@link here} for Posix/SUS C API. */ public native static void ftruncate(int fd, long length) throws UErrorException; /** Calls lchown. Click {@link here} for Posix/SUS C API. */ public native static void lchown(String path, long uid, long gid) throws UErrorException; /** Calls link. Click {@link here} for Posix/SUS C API. */ public native static void link(String oldpath, String newpath) throws UErrorException; /** Calls lockf. Click {@link here} for Posix/SUS C API. */ public native static void lockf(int fd, int op, long len) throws UErrorException; /** Calls lseek. Click {@link here} for Posix/SUS C API. */ public native static long lseek(int fd, long pos, int whence) throws UErrorException; /** Calls lstat. Click {@link here} for Posix/SUS C API. */ public native static void lstat(String path, s_stat buf) throws UErrorException; /** Calls mkfifo. Click {@link here} for Posix/SUS C API. */ public native static void mkfifo(String path, int perms) throws UErrorException; /** Calls mknod. Click {@link here} for Posix/SUS C API. */ public native static void mknod(String path, int mode, long dev) throws UErrorException; /** Calls mkstemp. Click {@link here} for Posix/SUS C API. */ public native static int mkstemp(StringBuffer template) throws UErrorException; /** Calls open. Click {@link here} for Posix/SUS C API. */ public native static int open(String path, int flags, int perms) throws UErrorException; /** Calls open. Click {@link here} for Posix/SUS C API. */ public static int open(String path, int flags) throws UErrorException { return open(path, flags, 0); } /** Calls pipe. Click {@link here} for Posix/SUS C API. */ public native static void pipe(int[] pfd) throws UErrorException; /** Calls poll. Click {@link here} for Posix/SUS C API. */ public native static int poll(s_pollfd[] fdinfo, int nfds, int timeout); /** Calls pread. Click {@link here} for Posix/SUS C API. */ public native static int pread(int fd, byte[] buf, int nbytes, long offset) throws UErrorException; /** Calls pselect. Click {@link here} for Posix/SUS C API. */ public native static int pselect(int nfds, fd_set readset, fd_set writeset, fd_set errorset, UProcess.s_timespec timeout, UProcess.sigset_t sigmask) throws UErrorException; /** Calls pwrite. Click {@link here} for Posix/SUS C API. */ public native static int pwrite(int fd, byte[] buf, int nbytes, long position) throws UErrorException; /** Calls read. Click {@link here} for Posix/SUS C API. */ public native static int read(int fd, byte[] buf, int nbytes) throws UErrorException; /** Calls readlink. Click {@link here} for Posix/SUS C API. */ public native static int readlink(String path, byte[] buf, int bufsize) throws UErrorException; /** Calls readv. Click {@link here} for Posix/SUS C API. */ public native static int readv(int fd, s_iovec[] iov, int iovcnt) throws UErrorException; /** Calls rename. Click {@link here} for Posix/SUS C API. */ public native static void rename(String oldpath, String newpath) throws UErrorException; /** Calls S_ISBLK. */ public native static boolean S_ISBLK(int mode); /** Calls S_ISCHR. */ public native static boolean S_ISCHR(int mode); /** Calls S_ISDIR. */ public native static boolean S_ISDIR(int mode); /** Calls S_ISFIFO. */ public native static boolean S_ISFIFO(int mode); /** Calls S_ISLNK. */ public native static boolean S_ISLNK(int mode); /** Calls S_ISREG. */ public native static boolean S_ISREG(int mode); /** Calls S_ISSOCK. */ public native static boolean S_ISSOCK(int mode); /** Calls select. Click {@link here} for Posix/SUS C API. */ public native static int select(int nfds, fd_set readset, fd_set writeset, fd_set errorset, UProcess.s_timeval timeout) throws UErrorException; /** Calls stat. Click {@link here} for Posix/SUS C API. */ public native static void stat(String path, s_stat buf) throws UErrorException; /** Calls statvfs. Click {@link here} for Posix/SUS C API. */ public native static void statvfs(String path, s_statvfs buf) throws UErrorException; /** Calls symlink. Click {@link here} for Posix/SUS C API. */ public native static void symlink(String oldpath, String newpath) throws UErrorException; /** Calls sync. Click {@link here} for Posix/SUS C API. */ public native static void sync(); /** Calls truncate. Click {@link here} for Posix/SUS C API. */ public native static void truncate(String path, long length) throws UErrorException; /** Calls unlink. Click {@link here} for Posix/SUS C API. */ public native static void unlink(String path) throws UErrorException; /** Calls utime. Click {@link here} for Posix/SUS C API. */ public native static void utime(String path, s_utimbuf timbuf) throws UErrorException; /** Calls write. Click {@link here} for Posix/SUS C API. */ /** Calls ioctl. Click {@link here} for Posix/SUS C API. */ public native static int ioctl(int fd, int request, byte[] buf) throws UErrorException; /** Calls ioctl. Click {@link here} for Posix/SUS C API. */ public native static int ioctl2(int fd, int request, int arg) throws UErrorException; /** Calls write. Click {@link here} for Posix/SUS C API. */ public native static int write(int fd, byte[] buf, int nbytes) throws UErrorException; /** Calls writev. Click {@link here} for Posix/SUS C API. */ public native static int writev(int fd, s_iovec[] iov, int iovcnt) throws UErrorException; }
blob data class, long method t t f data class, long method blob 0 8003 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/third_party/jtux/java/jtux/UFile.java/#L29-L460 1 875 8003
1731 { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } }
feature envy Long Method, Data Class t f f Long Method, Data Class feature envy 0 11820 https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 1 1731 11820
1290    { "output": "YES, I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } }
blob data class, long method t t f data class, long method blob 0 10616 https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 1 1290 10616
1667 {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; private final AbstractPathConfiguration classpathConfiguration; private final ClassLoaderConfiguration classLoaderConfiguration; private final boolean isForkRequested; private final boolean isInForkedVm; public StartupConfiguration( @Nonnull String providerClassName, @Nonnull AbstractPathConfiguration classpathConfiguration, @Nonnull ClassLoaderConfiguration classLoaderConfiguration, boolean isForkRequested, boolean inForkedVm ) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.isForkRequested = isForkRequested; this.providerClassName = providerClassName; isInForkedVm = inForkedVm; } public boolean isProviderMainClass() { return providerClassName.endsWith( "#main" ); } public static StartupConfiguration inForkedVm( String providerClassName, ClasspathConfiguration classpathConfiguration, ClassLoaderConfiguration classLoaderConfiguration ) { return new StartupConfiguration( providerClassName, classpathConfiguration, classLoaderConfiguration, true, true ); } public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } @Deprecated public boolean useSystemClassLoader() { // todo; I am not totally convinced this logic is as simple as it could be return classLoaderConfiguration.isUseSystemClassLoader() && ( isInForkedVm || isForkRequested ); } public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } public String getProviderClassName() { return providerClassName; } public String getActualClassName() { return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; } /** * Strip any of a supplied String from the end of a String. * * If the strip String is {@code null}, whitespace is * stripped. * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ private static String stripEnd( String str, String strip ) { if ( str == null ) { return null; } int end = str.length(); if ( strip == null ) { while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) { end--; } } else { while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) { end--; } } return str.substring( 0, end ); } public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } public boolean isShadefire() { return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); } public void writeSurefireTestClasspathProperty() { getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11625 https://github.com/apache/maven-surefire/blob/e57f76c7e858dbbaac6be4cbcd16e215de10b064/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java/#L29-L140 1 1667 11625
775 {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } }
blob data class t t f data class blob 0 7352 https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 1 775 7352
774   YES I found bad smellsThe bad smells are: 1. Long method 2. Data class 3. Feature envy 4. Primitive obsession I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } }
blob  Long method2 Data class3 Feature envy4 Primitive obsession t f f . Long method2. Data class3. Feature envy4. Primitive obsession blob 0 7350 https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 2 774 7350
2383 {"answer": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TimestampTracker implements AutoCloseable { private static final Logger log = LoggerFactory.getLogger(TimestampTracker.class); private volatile long zkTimestamp = -1; private final Environment env; private final SortedSet timestamps = new TreeSet<>(); private volatile PersistentNode node = null; private final TransactorID tid; private final Timer timer; private boolean closed = false; private int allocationsInProgress = 0; private boolean updatingZk = false; public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Objects.requireNonNull(env, "environment cannot be null"); Objects.requireNonNull(tid, "tid cannot be null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; TimerTask tt = new TimerTask() { private int sawZeroCount = 0; @Override public void run() { try { long ts = 0; synchronized (TimestampTracker.this) { if (closed) { return; } if (allocationsInProgress > 0) { sawZeroCount = 0; if (!timestamps.isEmpty()) { if (updatingZk) { throw new IllegalStateException("expected updatingZk to be false"); } ts = timestamps.first(); updatingZk = true; } } else if (allocationsInProgress == 0) { sawZeroCount++; if (sawZeroCount >= 2) { sawZeroCount = 0; closeZkNode(); } } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } // update can be done outside of sync block as timer has one thread and future // executions of run method will block until this method returns if (updatingZk) { try { updateZkNode(ts); } finally { synchronized (TimestampTracker.this) { updatingZk = false; } } } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); } public TimestampTracker(Environment env, TransactorID tid) { this(env, tid, env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT)); } /** * Allocate a timestamp */ public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } } /** * Remove a timestamp (of completed transaction) */ public synchronized void removeTimestamp(long ts) throws NoSuchElementException { Preconditions.checkState(!closed, "tracker closed "); Preconditions.checkState(allocationsInProgress > 0, "allocationsInProgress should be > 0 " + allocationsInProgress); Objects.requireNonNull(node); if (timestamps.remove(ts) == false) { throw new NoSuchElementException( "Timestamp " + ts + " was previously removed or does not exist"); } allocationsInProgress--; } private Stamp getTimestamp() { return env.getSharedResources().getOracleClient().getStamp(); } private void createZkNode(long ts) { Preconditions.checkState(node == null, "expected node to be null"); node = new PersistentNode(env.getSharedResources().getCurator(), CreateMode.EPHEMERAL, false, getNodePath(), LongUtil.toByteArray(ts)); CuratorUtil.startAndWait(node, 10); zkTimestamp = ts; } private void closeZkNode() { try { if (node != null) { node.close(); node = null; } } catch (IOException e) { log.error("Failed to close timestamp tracker ephemeral node"); throw new IllegalStateException(e); } } private void updateZkNode(long ts) { if (ts != zkTimestamp) { try { node.setData(LongUtil.toByteArray(ts)); } catch (Exception e) { throw new IllegalStateException(e); } } zkTimestamp = ts; } @VisibleForTesting public synchronized void updateZkNode() { Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); if (allocationsInProgress > 0) { if (!timestamps.isEmpty()) { updateZkNode(timestamps.first()); } } else if (allocationsInProgress == 0) { closeZkNode(); } else { throw new IllegalStateException("allocationsInProgress = " + allocationsInProgress); } } @VisibleForTesting public long getOldestActiveTimestamp() { return timestamps.first(); } @VisibleForTesting public long getZookeeperTimestamp() { return zkTimestamp; } @VisibleForTesting public boolean isEmpty() { return timestamps.isEmpty(); } @VisibleForTesting public String getNodePath() { return ZookeeperPath.TRANSACTOR_TIMESTAMPS + "/" + tid; } @Override public synchronized void close() { Preconditions.checkState(!closed, "tracker already closed"); closed = true; timer.cancel(); closeZkNode(); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 14341 https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/impl/TimestampTracker.java/#L41-L250 1 2383 14341
3543    {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } }
blob data class t t f data class blob 0 7716 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 1 3543 7716
106  { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } }
blob blob, data class t t t  data class   0 1407 https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 1 106 1407
478 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } }
blob data class t t f data class blob 0 4622 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 1 478 4622
179 { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BrocadeVcsApi { private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class); private final String _host; private final String _adminuser; private final String _adminpass; protected DefaultHttpClient _client; protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { String url; try { url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Brocade Switch API URL", e); throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); } if ("post".equalsIgnoreCase(type)) { return new HttpPost(url); } else if ("get".equalsIgnoreCase(type)) { return new HttpGet(url); } else if ("delete".equalsIgnoreCase(type)) { return new HttpDelete(url); } else if ("patch".equalsIgnoreCase(type)) { return new HttpPatch(url); } else { throw new BrocadeVcsApiException("Requesting unknown method type"); } } public BrocadeVcsApi(String address, String username, String password) { _host = address; _adminuser = username; _adminpass = password; _client = new DefaultHttpClient(); _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); } /* * Get Operational Status */ public Output getSwitchStatus() throws BrocadeVcsApiException { return executeRetreiveStatus(Constants.STATUS_URI); } /* * Creates a new virtual network. */ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (createInterfaceVlan(vlanId)) { final PortProfile portProfile = createPortProfile(vlanId, networkId); if (portProfile != null) { return activatePortProfile(portProfile); } } return false; } /* * Activates a port-profile. */ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); portProfile.setVlanProfile(null); final Activate activate = new Activate(); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Creates AMPP port-profile. */ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); if (executeCreateObject(portProfile, Constants.URI)) { if (createVlanSubProfile(vlanId, portProfile)) { return portProfile; } } return null; } /* * Create vlan sub-profile for port-profile */ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final VlanProfile vlanProfile = new VlanProfile(); portProfile.setVlanProfile(vlanProfile); if (executeUpdateObject(portProfile, Constants.URI)) { return configureVlanSubProfile(vlanId, portProfile); } return false; } /* * Configures vlan sub-profile for port-profile. * - configure L2 mode for vlan sub-profile * - configure trunk mode for vlan sub-profile * - configure allowed VLANs for vlan sub-profile */ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { final SwitchportBasic switchPortBasic = new SwitchportBasic(); final Basic basic = new Basic(); switchPortBasic.setBasic(basic); portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); // configure L2 mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { VlanProfile vlanProfile = new VlanProfile(); Switchport switchPort = new Switchport(); final Mode mode = new Mode(); mode.setVlanMode("trunk"); switchPort.setMode(mode); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); // configure trunk mode for vlan sub-profile if (executeUpdateObject(portProfile, Constants.URI)) { vlanProfile = new VlanProfile(); switchPort = new Switchport(); final Trunk trunk = new Trunk(); final Allowed allowed = new Allowed(); final Allowed.Vlan allowedVlan = new Allowed.Vlan(); allowedVlan.setAdd(vlanId); allowed.setVlan(allowedVlan); trunk.setAllowed(allowed); switchPort.setTrunk(trunk); vlanProfile.setSwitchport(switchPort); portProfile.setVlanProfile(vlanProfile); //configure allowed VLANs for vlan sub-profile return executeUpdateObject(portProfile, Constants.URI); } } return false; } /* * Creates a vlan interface. */ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Associates a MAC address to virtual network. */ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Disassociates a MAC address from virtual network. */ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Static staticObj = new Static(); staticObj.setOperation("delete"); staticObj.setMacAddress(macAddress); portProfile.setStatic(staticObj); portProfileGlobal.setPortProfile(portProfile); //associates a mac address to a port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes a new virtual network. */ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { if (deactivatePortProfile(networkId)) { if (deletePortProfile(networkId)) { return deleteInterfaceVlan(vlanId); } } return false; } /* * Deletes a vlan interface. */ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { final InterfaceVlan interfaceVlan = new InterfaceVlan(); final Interface interfaceObj = new Interface(); final Vlan vlan = new Vlan(); vlan.setOperation("delete"); vlan.setName(vlanId); interfaceObj.setVlan(vlan); interfaceVlan.setInterface(interfaceObj); return executeUpdateObject(interfaceVlan, Constants.URI); } /* * Deactivates a port-profile. */ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); final Activate activate = new Activate(); activate.setOperation("delete"); portProfile.setActivate(activate); portProfileGlobal.setPortProfile(portProfile); //activate port-profile return executeUpdateObject(portProfileGlobal, Constants.URI); } /* * Deletes AMPP port-profile. */ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { final PortProfile portProfile = new PortProfile(); portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); portProfile.setOperation("delete"); //deletes port-profile return executeUpdateObject(portProfile, Constants.URI); } protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { final boolean result = true; if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpPatch pm = (HttpPatch)createMethod("patch", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to update object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); } pm.releaseConnection(); return result; } protected String convertToString(T object) throws BrocadeVcsApiException { final StringWriter stringWriter = new StringWriter(); try { final JAXBContext context = JAXBContext.newInstance(object.getClass()); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, stringWriter); } catch (final JAXBException e) { s_logger.error("Failed to convert object to string : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); } final String str = stringWriter.toString(); s_logger.info(str); return str; } protected Output convertToXML(String object) throws BrocadeVcsApiException { Output output = null; try { final JAXBContext context = JAXBContext.newInstance(Output.class); final StringReader reader = new StringReader(object); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(reader); if (result instanceof Output) { output = (Output)result; s_logger.info(output); } } catch (final JAXBException e) { s_logger.error("Failed to convert string to object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); } return output; } protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final boolean result = true; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to create object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return result; } protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; final HttpPost pm = (HttpPost)createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); final HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while ((readLine = br.readLine()) != null) { s_logger.debug(readLine); sb.append(readLine); } } catch (final Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); } protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } final HttpDelete dm = (HttpDelete)createMethod("delete", uri); dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); final HttpResponse response = executeMethod(dm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (final IOException e) { s_logger.error("Failed to delete object : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); } dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); } protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { HttpResponse response = null; try { response = _client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); response = _client.execute(method); } } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Brocade Switch", e); method.releaseConnection(); throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); } return response; } private String responseToErrorMessage(HttpResponse response) throws IOException { if ("text/html".equals(response.getEntity().getContentType().getValue())) { try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } } return null; } }
blob long method, data class t t f long method, data class blob 0 2055 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java/#L63-L542 1 179 2055
877 { "answer": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } }
blob blob, data class t t t  data class   0 8011 https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 1 877 8011
1665 { "output": { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); }
long method Long Method, Data Class t f t  Data Class   0 11622 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 1 1665 11622
1938 { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } }
blob long method, data class t t f long method, data class blob 0 12477 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 1 1938 12477
5571  YES I found bad smells the bad smells are: Blob, Data Class, Feature Envy, Long Method The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } }
feature envy  Blob, Data Class, Feature Envy, Long Method t f t  Blob, Data Class, Long Method   0 8188 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 1 5571 8188
4353  {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } }
blob long method, data class t t f long method, data class blob 0 11498 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 1 4353 11498
1488     { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } }
blob long method, data class t t f long method, data class blob 0 11104 https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 1 1488 11104
365 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the serialized form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } }
blob long method, data class t t f long method, data class blob 0 3717 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/TokenMgrError.java/#L22-L162 1 365 3717
1251  {"response":"YES I found bad smells","bad smells are:":"1. Long method, 2. Feature envy, 3. Complex condition, 4. Comments, 5. Exception swallowing, 6. Data class, 7. Shotgun surgery"} I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } }
blob 1. long method, 2. feature envy, 3. complex condition, 4. comments, 5. exception swallowing, 6. data class, 7. shotgun surgery t t f 1. long method, 2. feature envy, 3. complex condition, 4. comments, 5. exception swallowing, 6. data class, 7. shotgun surgery blob 0 10441 https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 2 1251 10441
2700 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Output directory is specified by user") class AppInfoCollector { private final DiagOozieClient client; private final OozieLauncherLogFetcher oozieLauncherLogFetcher; AppInfoCollector(final Configuration hadoopConfig, final DiagOozieClient client) { this.client = client; oozieLauncherLogFetcher = new OozieLauncherLogFetcher(hadoopConfig); } private void storeWorkflowJobDetails(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isWorkflow(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File workflowOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(workflowOutputDir)) { return; } final File resolvedActionsDir = new File(workflowOutputDir, "resolved-actions"); if (!createOutputDirectory(resolvedActionsDir)) { System.out.println("Workflow details already stored."); return; } final WorkflowJob job = client.getJobInfo(jobId); try (DiagBundleEntryWriter diagBundleEntryWriter = new DiagBundleEntryWriter(workflowOutputDir,"info.txt")) { persistWorkflowJobInfo(maxChildActions, resolvedActionsDir, job, diagBundleEntryWriter); } storeCommonDetails(workflowOutputDir, jobId, "workflow", job.getConf()); System.out.println("Done"); } catch (IOException | OozieClientException e) { System.err.printf("Exception occurred during the retrieval of workflow information: %s%n", e.getMessage()); } } private void persistWorkflowJobInfo(int maxChildActions, final File resolvedActionsDir, final WorkflowJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("WORKFLOW\n") .writeString("--------\n") .writeStringValue("Workflow Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Parent Id : ", job.getParentId()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Modified Time : ", job.getLastModifiedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeIntValue("Run : ", job.getRun()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List workflowActions = job.getActions(); for (int actionCount = 0; actionCount != workflowActions.size() && actionCount < maxChildActions; ++actionCount) { final WorkflowAction action = workflowActions.get(actionCount); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeStringValue("Name : ", action.getName()) .writeStringValue("Type : ", action.getType()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("Transition : ", action.getTransition()) .writeDateValue("Start Time : ", action.getStartTime()) .writeDateValue("End Time : ", action.getEndTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeStringValue("External Child Ids : ", action.getExternalChildIDs()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Data : ", action.getData()) .writeStringValue("Stats : ", action.getStats()) .writeStringValue("Credentials : ", action.getCred()) .writeIntValue("Retries : ", action.getRetries()) .writeIntValue("User Retry Int : ", action.getUserRetryInterval()) .writeIntValue("User Retry Count : ", action.getUserRetryCount()) .writeIntValue("User Retry Max : ", action.getUserRetryMax()) .writeNewLine() .flush(); final String actionType = action.getType(); persistResolvedActionDefinition(action, resolvedActionsDir); if (!isControlNode(actionType)) { // skip control nodes storeOozieLauncherLog(resolvedActionsDir, action, job.getUser()); } } } private boolean isControlNode(final String actionType) { return isNonDecisionControlNode(actionType) || isDecisionNode(actionType); } private boolean isDecisionNode(final String actionType) { return actionType.contains("switch"); } private boolean isNonDecisionControlNode(final String actionType) { return actionType.contains(":"); } private void persistResolvedActionDefinition(final WorkflowAction action, final File resolvedActionsDir) throws IOException { persistWorkflowDefinition(resolvedActionsDir, action.getName(), action.getConf()); } private void storeOozieLauncherLog(final File outputDir, final WorkflowAction action, final String user) { try (PrintStream fw = new PrintStream(new File(outputDir, "launcher_" + action.getName() + ".log"), StandardCharsets.UTF_8.toString())) { final ApplicationId appId = ConverterUtils.toApplicationId(action.getExternalId()); oozieLauncherLogFetcher.dumpAllContainersLogs(appId, user, fw); } catch (IOException e) { System.err.printf("Exception occurred during the retrieval of Oozie launcher logs for workflow(s): %s%n", e.getMessage()); } } private void getCoordJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isCoordinator(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File coordOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(coordOutputDir)) { return; } final CoordinatorJob job = client.getCoordJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(coordOutputDir, "info.txt")) { persistCoordinatorJobInfo(maxChildActions, job, bundleEntryWriter); } storeCommonDetails(coordOutputDir, jobId, "coordinator", job.getConf()); System.out.println("Done"); final List coordinatorActions = job.getActions(); for (int i = 0; i != coordinatorActions.size() && i < maxChildActions; ++i) { storeWorkflowJobDetails(outputDir, coordinatorActions.get(i).getExternalId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of coordinator information:%s%n", e.getMessage())); } } private void persistCoordinatorJobInfo(int maxChildActions, final CoordinatorJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("COORDINATOR\n") .writeString("-----------\n") .writeStringValue("Coordinator Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("ACL : ", job.getAcl()) .writeStringValue("Status : ", job.getStatus().toString()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue("External Id : ", job.getExternalId()) .writeStringValue("Bundle Id : ", job.getBundleId()) .writeStringValue("Frequency : ", job.getFrequency()) .writeStringValue("Time Unit : ", job.getTimeUnit().toString()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("Last Action Time : ", job.getLastActionTime()) .writeDateValue("Next Materialized Time : ", job.getNextMaterializedTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeStringValue("Timezone : ", job.getTimeZone()) .writeIntValue("Concurrency : ", job.getConcurrency()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Execution Order : ", job.getExecutionOrder().toString()) .writeIntValue("Action Count : ", job.getActions().size()) .writeNewLine() .writeString("ACTIONS\n") .writeString("------\n") .flush(); final List coordinatorActions = job.getActions(); for (int i = 0; i < maxChildActions && i != coordinatorActions.size(); ++i) { final CoordinatorAction action = coordinatorActions.get(i); bundleEntryWriter.writeStringValue("Action Id : ", action.getId()) .writeIntValue("Action Number : ", action.getActionNumber()) .writeStringValue("Job Id : ", action.getJobId()) .writeStringValue("Status : ", action.getStatus().toString()) .writeStringValue("External Id : ", action.getExternalId()) .writeStringValue("External Status : ", action.getExternalStatus()) .writeStringValue("Console URL : ", action.getConsoleUrl()) .writeStringValue("Tracker URI : ", action.getTrackerUri()) .writeDateValue("Created Time : ", action.getCreatedTime()) .writeDateValue("Nominal Time : ", action.getNominalTime()) .writeDateValue("Last Modified Time : ", action.getLastModifiedTime()) .writeStringValue("Error Code : ", action.getErrorCode()) .writeStringValue("Error Message : ", action.getErrorMessage()) .writeStringValue("Missing Dependencies : ", action.getMissingDependencies()) .writeStringValue("Push Missing Dependencies : ", action.getPushMissingDependencies()) .writeNewLine() .flush(); } } private void getBundleJob(final File outputDir, final String jobId, int maxChildActions) { if (jobId == null || !isBundle(jobId)) { return; } try { System.out.print("Getting Details for " + jobId + "..."); final File bundleOutputDir = new File(outputDir, jobId); if (!createOutputDirectory(bundleOutputDir)) { return; } final BundleJob job = client.getBundleJobInfo(jobId); try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(bundleOutputDir, "info.txt")) { persistBundleJobInfo(job, bundleEntryWriter); } storeCommonDetails(bundleOutputDir, jobId, "bundle", job.getConf()); System.out.println("Done"); for (CoordinatorJob coordJob : job.getCoordinators()) { getCoordJob(outputDir, coordJob.getId(), maxChildActions); } } catch (IOException | OozieClientException e) { System.err.printf(String.format("Exception occurred during the retrieval of bundle information: %s%n", e.getMessage())); } } private boolean createOutputDirectory(final File outputDir) throws IOException { if (outputDir.isDirectory()) { System.out.println("(Already) Done"); return false; } if (!outputDir.mkdirs()) { throw new IOException("Could not create output directory: " + outputDir.getAbsolutePath()); } return true; } private void persistBundleJobInfo(final BundleJob job, final DiagBundleEntryWriter bundleEntryWriter) throws IOException { bundleEntryWriter.writeString("BUNDLE\n") .writeString("-----------\n") .writeStringValue("Bundle Id : ", job.getId()) .writeStringValue("Name : ", job.getAppName()) .writeStringValue("App Path : ", job.getAppPath()) .writeStringValue("User : ", job.getUser()) .writeStringValue("Status : ", job.getStatus().toString()) .writeDateValue("Created Time : ", job.getCreatedTime()) .writeDateValue("Start Time : ", job.getStartTime()) .writeDateValue("End Time : ", job.getEndTime()) .writeDateValue("KickoffTime : ", job.getKickoffTime()) .writeDateValue("Pause Time : ", job.getPauseTime()) .writeIntValue("Timeout : ", job.getTimeout()) .writeStringValue("Console URL : ", job.getConsoleUrl()) .writeStringValue( "ACL : ", job.getAcl()) .flush(); } private void storeCommonDetails(final File outputDir, final String jobId, final String definitionName, final String jobPropsConfStr) { try { final String definition = client.getJobDefinition(jobId); if (definition != null) { persistWorkflowDefinition(outputDir, definitionName, definition); } if (jobPropsConfStr != null) { persistJobProperties(outputDir, jobPropsConfStr); } persistJobLog(outputDir, jobId); } catch (OozieClientException | IOException e) { System.err.printf(String.format("Exception occurred during the retrieval of common job details: %s%n", e.getMessage())); } } private void persistJobLog(final File outputDir, final String jobId) throws FileNotFoundException, UnsupportedEncodingException, OozieClientException { try (PrintStream ps = new PrintStream(new File(outputDir, "log.txt"), StandardCharsets.UTF_8.toString())) { client.getJobLog(jobId, null, null, null, ps); } } private void persistJobProperties(final File outputDir, final String jobPropsConfStr) throws IOException { final StringReader sr = new StringReader(jobPropsConfStr); final XConfiguration jobPropsConf = new XConfiguration(sr); final Properties jobProps = jobPropsConf.toProperties(); try (OutputStream outputStream = new FileOutputStream(new File(outputDir, "job.properties"))) { jobProps.store(outputStream, ""); } } private void persistWorkflowDefinition(final File outputDir, final String definitionName, String definition) throws IOException { try (DiagBundleEntryWriter bundleEntryWriter = new DiagBundleEntryWriter(outputDir, definitionName + ".xml")) { bundleEntryWriter.writeString(definition); } } void storeLastWorkflows(final File outputDir, int numWorkflows, int maxChildActions) { if (numWorkflows == 0) { return; } try { final List jobs = client.getJobsInfo(null, 0, numWorkflows); for (WorkflowJob job : jobs) { storeWorkflowJobDetails(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d workflow(s): %s.%n", numWorkflows, e.getMessage()); } } void storeLastCoordinators(final File outputDir, int numCoordinators, int maxChildActions) { if (numCoordinators == 0) { return; } try { final List jobs = client.getCoordJobsInfo(null, 0, numCoordinators); for (CoordinatorJob job : jobs) { getCoordJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d coordinator(s): %s.%n", numCoordinators, e.getMessage()); } } void storeLastBundles(final File outputDir, int numBundles, int maxChildActions) { if (numBundles == 0) { return; } try { final List jobs = client.getBundleJobsInfo(null, 0, numBundles); for (BundleJob job : jobs) { getBundleJob(outputDir, job.getId(), maxChildActions); } } catch (OozieClientException e) { System.err.printf("Exception occurred during the retrieval of information on the last %d bundle(s): %s.%n", numBundles, e.getMessage()); } } void getSpecificJobs(final File outputDir, final String[] jobIds, int maxChildActions) { if (jobIds == null) { return; } for (String jobId : jobIds) { if (isWorkflow(jobId)) { storeWorkflowJobDetails(outputDir, jobId, maxChildActions); } else if (isCoordinator(jobId)) { getCoordJob(outputDir, jobId, maxChildActions); } else if (isBundle(jobId)) { getBundleJob(outputDir, jobId, maxChildActions); } } } private boolean isBundle(final String jobId) { return jobId.endsWith("-B"); } private boolean isCoordinator(final String jobId) { return jobId.endsWith("-C"); } private boolean isWorkflow(final String jobId) { return jobId.endsWith("-W"); } }
blob long method, data class t t f long method, data class blob 0 15327 https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/tools/src/main/java/org/apache/oozie/tools/diag/AppInfoCollector.java/#L45-L443 1 2700 15327
5732  YES I found bad smells the bad smells are: 1. Data Class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } }
long method  Data Class t f f . Data Class long method 0 13493 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 1 5732 13493
180
{
"message": "YES, I found bad smells",
"the bad smells are:": [
"Long method",
"Data class",
"Feature envy"
]
}
I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } }
blob long method, data class, feature envy t t f long method, data class, feature envy blob 0 2063 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 2 180 2063
1542 {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } }
blob long method, data class t t f long method, data class blob 0 11240 https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 1 1542 11240
2618 { "output": "YES I found bad smells, the bad smells are: Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } }
blob data class t t f data class blob 0 15050 https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 1 2618 15050
4059  {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } }
blob data class t t f data class blob 0 10711 https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 1 4059 10711
2578 {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component public class UsageServiceImpl extends ManagerBase implements UsageService, Manager { public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class); //ToDo: Move implementation to ManagaerImpl @Inject private AccountDao _accountDao; @Inject private DomainDao _domainDao; @Inject private UsageDao _usageDao; @Inject private UsageJobDao _usageJobDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectManager _projectMgr; private TimeZone _usageTimezone; @Inject private AccountService _accountService; @Inject private VMInstanceDao _vmDao; @Inject private SnapshotDao _snapshotDao; @Inject private SecurityGroupDao _sgDao; @Inject private VpnUserDao _vpnUserDao; @Inject private PortForwardingRulesDao _pfDao; @Inject private LoadBalancerDao _lbDao; @Inject private VMTemplateDao _vmTemplateDao; @Inject private VolumeDao _volumeDao; @Inject private IPAddressDao _ipDao; @Inject private HostDao _hostDao; public UsageServiceImpl() { } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } _usageTimezone = TimeZone.getTimeZone(timeZoneStr); return true; } @Override public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob(); if (immediateJob == null) { UsageJobVO job = _usageJobDao.getLastJob(); String host = null; int pid = 0; if (job != null) { host = job.getHost(); pid = ((job.getPid() == null) ? 0 : job.getPid().intValue()); } _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE); } } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return true; } @Override public Pair, Integer> getUsageRecords(GetUsageRecordsCmd cmd) { Long accountId = cmd.getAccountId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Account userAccount = null; Account caller = CallContext.current().getCallingAccount(); Long usageType = cmd.getUsageType(); Long projectId = cmd.getProjectId(); String usageId = cmd.getUsageId(); if (projectId != null) { if (accountId != null) { throw new InvalidParameterValueException("Projectid and accountId can't be specified together"); } Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } accountId = project.getProjectAccountId(); } //if accountId is not specified, use accountName and domainId if ((accountId == null) && (accountName != null) && (domainId != null)) { if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) { Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null); List accounts = _accountDao.listAccounts(accountName, domainId, filter); if (accounts.size() > 0) { userAccount = accounts.get(0); } if (userAccount != null) { accountId = userAccount.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } } else { throw new PermissionDeniedException("Invalid Domain Id or Account"); } } boolean isAdmin = false; boolean isDomainAdmin = false; //If accountId couldn't be found using accountName and domainId, get it from userContext if (accountId == null) { accountId = caller.getId(); //List records for all the accounts if the caller account is of type admin. //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin if (_accountService.isRootAdmin(caller.getId())) { isAdmin = true; } else if (_accountService.isDomainAdmin(caller.getId())) { isDomainAdmin = true; } s_logger.debug("Account details not available. Using userContext accountId: " + accountId); } Date startDate = cmd.getStartDate(); Date endDate = cmd.getEndDate(); if (startDate.after(endDate)) { throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate); } TimeZone usageTZ = getUsageTimezone(); Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ); Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ); if (s_logger.isDebugEnabled()) { s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex()); } Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _usageDao.createSearchCriteria(); if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (isDomainAdmin) { SearchCriteria sdc = _domainDao.createSearchCriteria(); sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%"); List domains = _domainDao.search(sdc, null); List domainIds = new ArrayList(); for (DomainVO domain : domains) domainIds.add(domain.getId()); sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray()); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if (usageType != null) { sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType); } if (usageId != null) { if (usageType == null) { throw new InvalidParameterValueException("Usageid must be specified together with usageType"); } Long usageDbId = null; switch (usageType.intValue()) { case UsageTypes.NETWORK_BYTES_RECEIVED: case UsageTypes.NETWORK_BYTES_SENT: case UsageTypes.RUNNING_VM: case UsageTypes.ALLOCATED_VM: case UsageTypes.VM_SNAPSHOT: VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId); if (vm != null) { usageDbId = vm.getId(); } if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) { HostVO host = _hostDao.findByUuidIncludingRemoved(usageId); if (host != null) { usageDbId = host.getId(); } } break; case UsageTypes.SNAPSHOT: SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId); if (snap != null) { usageDbId = snap.getId(); } break; case UsageTypes.TEMPLATE: case UsageTypes.ISO: VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId); if (tmpl != null) { usageDbId = tmpl.getId(); } break; case UsageTypes.LOAD_BALANCER_POLICY: LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId); if (lb != null) { usageDbId = lb.getId(); } break; case UsageTypes.PORT_FORWARDING_RULE: PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId); if (pf != null) { usageDbId = pf.getId(); } break; case UsageTypes.VOLUME: case UsageTypes.VM_DISK_IO_READ: case UsageTypes.VM_DISK_IO_WRITE: case UsageTypes.VM_DISK_BYTES_READ: case UsageTypes.VM_DISK_BYTES_WRITE: VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId); if (volume != null) { usageDbId = volume.getId(); } break; case UsageTypes.VPN_USERS: VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId); if (vpnUser != null) { usageDbId = vpnUser.getId(); } break; case UsageTypes.SECURITY_GROUP: SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId); if (sg != null) { usageDbId = sg.getId(); } break; case UsageTypes.IP_ADDRESS: IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId); if (ip != null) { usageDbId = ip.getId(); } break; default: break; } if (usageDbId != null) { sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId); } else { // return an empty list if usageId was not found return new Pair, Integer>(new ArrayList(), new Integer(0)); } } if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) { sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate); } else { return new Pair, Integer>(new ArrayList(), new Integer(0)); // return an empty list if we fail to validate the dates } Pair, Integer> usageRecords = null; TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter); } finally { txn.close(); // switch back to VMOPS_DB TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); swap.close(); } return new Pair, Integer>(usageRecords.first(), usageRecords.second()); } @Override public TimeZone getUsageTimezone() { return _usageTimezone; } @Override public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException { Integer interval = cmd.getInterval(); if (interval != null && interval > 0 ) { String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString()); if (jobExecTime != null ) { String[] segments = jobExecTime.split(":"); if (segments.length == 2) { String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString()); if (timeZoneStr == null) { timeZoneStr = "GMT"; } TimeZone tz = TimeZone.getTimeZone(timeZoneStr); Calendar cal = Calendar.getInstance(tz); cal.setTime(new Date()); long curTS = cal.getTimeInMillis(); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0])); cal.set(Calendar.MINUTE, Integer.parseInt(segments[1])); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long execTS = cal.getTimeInMillis(); s_logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS); // Let's avoid cleanup when job runs and around a 15 min interval if (Math.abs(curTS - execTS) < 15 * 60 * 1000) { return false; } } } _usageDao.removeOldUsageRecords(interval); } else { throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0"); } return true; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ) { Calendar cal = Calendar.getInstance(); cal.setTime(initialDate); TimeZone localTZ = cal.getTimeZone(); int timezoneOffset = cal.get(Calendar.ZONE_OFFSET); if (localTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } cal.add(Calendar.MILLISECOND, timezoneOffset); Date newTime = cal.getTime(); Calendar calTS = Calendar.getInstance(targetTZ); calTS.setTime(newTime); timezoneOffset = calTS.get(Calendar.ZONE_OFFSET); if (targetTZ.inDaylightTime(initialDate)) { timezoneOffset += (60 * 60 * 1000); } calTS.add(Calendar.MILLISECOND, -1 * timezoneOffset); return calTS.getTime(); } @Override public List listUsageTypes() { return UsageTypes.listUsageTypes(); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 14936 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/usage/UsageServiceImpl.java/#L79-L438 1 2578 14936
775   YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3. Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4. Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5. Complex conditional logic (onInit() method has long and complex if/else logic) 6. Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7. Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8. Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9. Speculative generality (expectReply variable is not used for anything other than setting it to true or false) 10.Comments/dead code (setGenerateDestinationDirectory method is never used) 11.Magic numbers (destinationDirectoryFormat variable has a string value that is not explained or easily understood) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class FsShellWritingMessageHandler extends AbstractReplyProducingMessageHandler { private volatile FileExistsMode fileExistsMode = FileExistsMode.REPLACE; private static final Log log = LogFactory .getLog(FsShellWritingMessageHandler.class); private volatile FileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); private final Expression destinationDirectoryExpression; private volatile boolean autoCreateDirectory = true; private volatile boolean deleteSourceFiles; private volatile boolean expectReply = false; private Configuration configuration; private FsShell fsShell; private volatile boolean generateDestinationDirectory = true; private volatile String destinationDirectoryFormat = "%1$tY/%1$tm/%1$td/%1$tH/%1$tM/%1$tS"; /** * Constructor which sets the {@link #destinationDirectoryExpression} using * a {@link LiteralExpression}. * * @param destinationDirectory * Must not be null * @see #FsShellWritingMessageHandler(Expression) */ public FsShellWritingMessageHandler(String destinationDirectory, Configuration configuration) { Assert.notNull(destinationDirectory, "Destination directory must not be null."); this.destinationDirectoryExpression = new LiteralExpression( destinationDirectory); createFsShell(configuration); } /** * Constructor which sets the {@link #destinationDirectoryExpression}. * * @param destinationDirectoryExpression * Must not be null * @see #FileWritingMessageHandler(String) */ public FsShellWritingMessageHandler( Expression destinationDirectoryExpression) { Assert.notNull(destinationDirectoryExpression, "Destination directory expression must not be null."); this.destinationDirectoryExpression = destinationDirectoryExpression; createFsShell(configuration); } private void createFsShell(Configuration configuration) { Assert.notNull(configuration, "Hadoop Configuration must not be null."); this.configuration = configuration; fsShell = new FsShell(configuration); } /** * Provide the {@link FileNameGenerator} strategy to use when generating the * destination file's name. */ public void setFileNameGenerator(FileNameGenerator fileNameGenerator) { Assert.notNull(fileNameGenerator, "FileNameGenerator must not be null"); this.fileNameGenerator = fileNameGenerator; } /** * Specify whether to delete source Files after writing to the destination * directory. The default is false. When set to true, it * will only have an effect if the inbound Message has a File payload or a * {@link FileHeaders#ORIGINAL_FILE} header value containing either a File * instance or a String representing the original file path. */ public void setDeleteSourceFiles(boolean deleteSourceFiles) { this.deleteSourceFiles = deleteSourceFiles; } /** * Will set the {@link FileExistsMode} that specifies what will happen in * case the destination exists. For example {@link FileExistsMode#APPEND} * instructs this handler to append data to the existing file rather then * creating a new file for each {@link Message}. * * If set to {@link FileExistsMode#APPEND}, the adapter will also create a * real instance of the {@link LockRegistry} to ensure that there is no * collisions when multiple threads are writing to the same file. * * Otherwise the LockRegistry is set to {@link PassThruLockRegistry} which * has no effect. * * @param fileExistsMode * Must not be null */ public void setFileExistsMode(FileExistsMode fileExistsMode) { Assert.notNull(fileExistsMode, "'fileExistsMode' must not be null."); this.fileExistsMode = fileExistsMode; } /** * Specify whether a reply Message is expected. If not, this handler will * simply return null for a successful response or throw an Exception for a * non-successful response. The default is true. */ public void setExpectReply(boolean expectReply) { this.expectReply = expectReply; } public void setGenerateDestinationDirectory(boolean generateDestinationDirectory) { this.generateDestinationDirectory = generateDestinationDirectory; } public void setDestinationDirectoryFormat(String destinationDirectoryFormat) { this.destinationDirectoryFormat = destinationDirectoryFormat; } @Override public final void onInit() { Assert.notNull(configuration, "Hadoop configuration must not be null"); fsShell = new FsShell(configuration); this.evaluationContext.addPropertyAccessor(new MapAccessor()); final BeanFactory beanFactory = this.getBeanFactory(); if (beanFactory != null) { this.evaluationContext.setBeanResolver(new BeanFactoryResolver( beanFactory)); } if (this.destinationDirectoryExpression instanceof LiteralExpression) { final Path directory = new Path( this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } } private void validateDestinationDirectory(Path destinationDirectory, boolean autoCreateDirectory) { // TODO } @Override protected Object handleRequestMessage(Message requestMessage) { Assert.notNull(requestMessage, "message must not be null"); Object payload = requestMessage.getPayload(); Assert.notNull(payload, "message payload must not be null"); String generatedFileName = this.fileNameGenerator .generateFileName(requestMessage); File originalFileFromHeader = this .retrieveOriginalFileFromHeader(requestMessage); final Path destinationDirectoryToUse = evaluateDestinationDirectoryExpression(requestMessage); Path resultFile = new Path(destinationDirectoryToUse, generatedFileName); boolean resultFileExists = fsShell.test(resultFile.toUri().toString()); if (FileExistsMode.FAIL.equals(this.fileExistsMode) && resultFileExists) { throw new MessageHandlingException(requestMessage, "The destination file already exists at '" + resultFile.toString() + "'."); } final boolean ignore = FileExistsMode.IGNORE .equals(this.fileExistsMode) && resultFileExists; if (!ignore) { try { if (payload instanceof File) { resultFile = this.handleFileMessage((File) payload, resultFile, resultFileExists); } else { throw new IllegalArgumentException( "unsupported Message payload type [" + payload.getClass().getName() + "]"); } } catch (Exception e) { throw new MessageHandlingException(requestMessage, "failed to write Message payload to file", e); } } if (!this.expectReply) { return null; } if (resultFile != null) { if (originalFileFromHeader == null && payload instanceof File) { return MessageBuilder.withPayload(resultFile).setHeader( FileHeaders.ORIGINAL_FILE, payload); } } return resultFile; } /** * Retrieves the File instance from the {@link FileHeaders#ORIGINAL_FILE} * header if available. If the value is not a File instance or a String * representation of a file path, this will return null. */ private File retrieveOriginalFileFromHeader(Message message) { Object value = message.getHeaders().get(FileHeaders.ORIGINAL_FILE); if (value instanceof File) { return (File) value; } if (value instanceof String) { return new File((String) value); } return null; } private Path handleFileMessage(final File sourceFile, Path resultFile, boolean resultFileExists) { if (FileExistsMode.REPLACE.equals(this.fileExistsMode) && resultFileExists) { fsShell.rm(resultFile.toString()); } log.info("sourceFile = " + sourceFile.getAbsolutePath()); log.info("resultFile = " + resultFile.toString()); fsShell.copyFromLocal(sourceFile.getAbsolutePath(), resultFile.toString()); cleanUpAfterCopy(sourceFile); return resultFile; } private void cleanUpAfterCopy(File originalFile) { if (this.deleteSourceFiles && originalFile != null) { originalFile.delete(); } } private Path evaluateDestinationDirectoryExpression(Message message) { final Path destinationDirectory; final Object destinationDirectoryToUse = this.destinationDirectoryExpression .getValue(this.evaluationContext, message); if (destinationDirectoryToUse == null) { throw new IllegalStateException( String.format( "The provided " + "destinationDirectoryExpression (%s) must not resolve to null.", this.destinationDirectoryExpression .getExpressionString())); } else if (destinationDirectoryToUse instanceof String) { String destinationDirectoryPath = (String) destinationDirectoryToUse; Assert.hasText( destinationDirectoryPath, String.format( "Unable to resolve destination directory name for the provided Expression '%s'.", this.destinationDirectoryExpression .getExpressionString())); if (this.generateDestinationDirectory) { destinationDirectoryPath = destinationDirectoryPath + "/" + PathUtils.format(this.destinationDirectoryFormat); } destinationDirectory = new Path(destinationDirectoryPath); } else if (destinationDirectoryToUse instanceof Path) { destinationDirectory = (Path) destinationDirectoryToUse; } else { throw new IllegalStateException(String.format("The provided " + "destinationDirectoryExpression (%s) must be of type " + "java.io.File or be a String.", this.destinationDirectoryExpression.getExpressionString())); } validateDestinationDirectory(destinationDirectory, this.autoCreateDirectory); return destinationDirectory; } }
blob  Long method 2 Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3 Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4 Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5 Complex conditional logic (onInit() method has long and complex if/else logic) 6 Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7 Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8 Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9 Speculative generality (expectReply variable is not used for anything other than setting it to true or false) t f f . Long method 2. Duplicate code/long method (createFsShell, onInit methods have duplicate code) 3. Feature envy/data clumps (handling request message, for example accessing request message properties like payload, headers) 4. Parallel inheritance hierarchies (using AbstractReplyProducingMessageHandler as a parent class, but not fully utilizing its functionality) 5. Complex conditional logic (onInit() method has long and complex if/else logic) 6. Primitive obsession (using fileExistsMode variable to represent different modes rather than creating a separate class for it) 7. Refused bequest (inheriting from AbstractReplyProducingMessageHandler but not fully utilizing its functionality) 8. Data class (FsShellWritingMessageHandler class simply contains a list of variables with getters and setters) 9. Speculative generality (expectReply variable is not used for anything other than setting it to true or false) blob 0 7352 https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/hadoop/file-polling/src/main/java/com/oreilly/springdata/hadoop/filepolling/FsShellWritingMessageHandler.java/#L27-L315 2 775 7352
670  {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 6553 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 1 670 6553
615  { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } }
blob data class t t f data class blob 0 6174 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 1 615 6174
820   { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class LibraryBreadcrumbNodeProvider extends DesignerBreadcrumbNodeProvider { public boolean validate( Object element ) { if ( getEditPart( element ) == null // || getEditPart( element ) instanceof EmptyEditPart ) return false; return true; } public EditPart getEditPart( Object element ) { // EditPart editPart = super.getEditPart( element ); // if ( editPart == null || editPart instanceof EmptyEditPart ) // return null; return super.getEditPart( element ); } @Override public Object[] getChildren( Object element ) { if ( getRealModel( element ) instanceof LibraryHandle ) { return ( (LibraryHandle) getRealModel( element ) ).getComponents( ) .getContents( ) .toArray( ); } List children = new ArrayList( ); children.addAll( Arrays.asList( super.getChildren( element ) ) ); for ( int i = 0; i < children.size( ); i++ ) { if ( children.get( i ) instanceof EmptyEditPart ) { children.remove( i ); i--; } } return children.toArray( ); } @Override public String getText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeDisplayName( object ); } } return super.getText( element ); } @Override public Image getImage( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return null; return provider.getNodeIcon( object ); } } return super.getImage( element ); } @Override public String getTooltipText( Object element ) { Object object = getRealModel( element ); if ( getEditPart( object ) == null ) { if ( object instanceof DesignElementHandle && ( (DesignElementHandle) object ).getContainer( ) instanceof LibraryHandle ) { INodeProvider provider = ProviderFactory.createProvider( object ); if ( provider == null ) return object.toString( ); return provider.getNodeTooltip( object ); } } return super.getTooltipText( element ); } }
blob data class t t f data class blob 0 7679 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.lib/src/org/eclipse/birt/report/designer/internal/lib/providers/LibraryBreadcrumbNodeProvider.java/#L31-L127 1 820 7679
1502      { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); }
long method long method, data class t t t  data class   0 11135 https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 1 1502 11135
1913 { "response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); }
long method 1. long method, 2. data class t t t  2. data class   0 12402 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 1 1913 12402
808    { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ScriptValueImpl extends ActionValueImpl implements ScriptValue { /** * The default value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected static final String SCRIPT_EDEFAULT = null; /** * The cached value of the '{@link #getScript() Script}' attribute. * * @see #getScript() * @generated * @ordered */ protected String script = SCRIPT_EDEFAULT; /** * * @generated */ protected ScriptValueImpl( ) { super( ); } /** * * @generated */ @Override protected EClass eStaticClass( ) { return AttributePackage.Literals.SCRIPT_VALUE; } /** * * @generated */ public String getScript( ) { return script; } /** * * @generated */ public void setScript( String newScript ) { String oldScript = script; script = newScript; if ( eNotificationRequired( ) ) eNotify( new ENotificationImpl( this, Notification.SET, AttributePackage.SCRIPT_VALUE__SCRIPT, oldScript, script ) ); } /** * * * @generated */ @Override public Object eGet( int featureID, boolean resolve, boolean coreType ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return getScript( ); } return super.eGet( featureID, resolve, coreType ); } /** * * * @generated */ @Override public void eSet( int featureID, Object newValue ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( (String) newValue ); return; } super.eSet( featureID, newValue ); } /** * * * @generated */ @Override public void eUnset( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : setScript( SCRIPT_EDEFAULT ); return; } super.eUnset( featureID ); } /** * * * @generated */ @Override public boolean eIsSet( int featureID ) { switch ( featureID ) { case AttributePackage.SCRIPT_VALUE__SCRIPT : return SCRIPT_EDEFAULT == null ? script != null : !SCRIPT_EDEFAULT.equals( script ); } return super.eIsSet( featureID ); } /** * * @generated */ @Override public String toString( ) { if ( eIsProxy( ) ) return super.toString( ); StringBuffer result = new StringBuffer( super.toString( ) ); result.append( " (script: " ); //$NON-NLS-1$ result.append( script ); result.append( ')' ); return result.toString( ); } /** * A convenience method provided to build a script action value when needed * * @param script * @return */ public static final ScriptValue create( String script ) { ScriptValue sv = AttributeFactory.eINSTANCE.createScriptValue( ); sv.setScript( script ); return sv; } /** * A convenient method to get an instance copy. This is much faster than the * ECoreUtil.copy(). */ public ScriptValue copyInstance( ) { ScriptValueImpl dest = new ScriptValueImpl( ); dest.set( this ); return dest; } protected void set( ScriptValue src ) { super.set( src ); script = src.getScript( ); } /* * Get script expression. * * @return expression the script expression. */ public ScriptExpression getScriptExpression( ) { ScriptExpression expression = new ScriptExpression( ); expression.setType( ChartUtil.getExpressionType( script ) ); expression.setValue( ChartUtil.getExpressionText( script ) ); return expression; } /* * Set script expression. * * @param expression the script expression. */ public void setScriptExpression( ScriptExpression expression ) { setScript( ChartUtil.adaptExpression( expression ) ); } } // ScriptValueImpl
blob data class t t f data class blob 0 7627 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/model/attribute/impl/ScriptValueImpl.java/#L35-L237 1 808 7627
282   { "message": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ImportDsmlRunnable implements StudioConnectionBulkRunnableWithProgress { /** The connection to use */ private IBrowserConnection browserConnection; /** The DSML file to use */ private File dsmlFile; /** The Save file to use */ private File responseFile; /** * LDAP Codec used by DSML parser * @TODO by Alex - this should be removed completely */ private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The connection to use * @param dsmlFile * The DSML file to read from * @param saveFile * The Save file to use * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile, File saveFile ) { this.browserConnection = connection; this.dsmlFile = dsmlFile; this.responseFile = saveFile; } /** * Creates a new instance of ImportDsmlRunnable. * * @param connection * The Connection to use * @param dsmlFile * The DSML file to read from * @param continueOnError * The ContinueOnError flag */ public ImportDsmlRunnable( IBrowserConnection connection, File dsmlFile ) { this( connection, dsmlFile, null ); } /** * {@inheritDoc} */ public Connection[] getConnections() { return new Connection[] { browserConnection.getConnection() }; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__import_dsml_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List l = new ArrayList(); l.add( browserConnection.getUrl() + "_" + DigestUtils.shaHex( dsmlFile.toString() ) ); //$NON-NLS-1$ return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return BrowserCoreMessages.jobs__import_dsml_error; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( BrowserCoreMessages.jobs__import_dsml_task, 2 ); monitor.reportProgress( " " ); //$NON-NLS-1$ monitor.worked( 1 ); try { // Parsing the file Dsmlv2Grammar grammar = new Dsmlv2Grammar(); Dsmlv2Parser parser = new Dsmlv2Parser( grammar ); parser.setInput( new FileInputStream( dsmlFile ), "UTF-8" ); //$NON-NLS-1$ parser.parseAllRequests(); // Getting the batch request BatchRequestDsml batchRequest = parser.getBatchRequest(); // Creating a DSML batch response (only if needed) BatchResponseDsml batchResponseDsml = null; if ( responseFile != null ) { batchResponseDsml = new BatchResponseDsml(); } // Setting the errors counter int errorsCount = 0; // Creating a dummy monitor that will be used to check if something // went wrong when executing the request StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); // Processing each request List> requests = batchRequest.getRequests(); for ( DsmlDecorator request : requests ) { // Processing the request processRequest( request, batchResponseDsml, dummyMonitor ); // Verifying if any error has been reported if ( dummyMonitor.errorsReported() ) { errorsCount++; } dummyMonitor.reset(); } // Writing the DSML response file to its final destination file. if ( responseFile != null ) { FileOutputStream fos = new FileOutputStream( responseFile ); OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" ); //$NON-NLS-1$ BufferedWriter bufferedWriter = new BufferedWriter( osw ); bufferedWriter.write( batchResponseDsml.toDsml() ); bufferedWriter.close(); osw.close(); fos.close(); } // Displaying an error message if we've had some errors if ( errorsCount > 0 ) { monitor.reportError( BrowserCoreMessages.bind( BrowserCoreMessages.dsml__n_errors_see_responsefile, new String[] { "" + errorsCount } ) ); //$NON-NLS-1$ } } catch ( Exception e ) { monitor.reportError( e ); } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { EventRegistry.fireEntryUpdated( new BulkModificationEvent( browserConnection ), this ); } /** * Processes the request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws LdapException */ private void processRequest( DsmlDecorator request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { switch ( request.getDecorated().getType() ) { case BIND_REQUEST: processBindRequest( ( BindRequest ) request, batchResponseDsml, monitor ); break; case ADD_REQUEST: processAddRequest( ( AddRequest ) request, batchResponseDsml, monitor ); break; case COMPARE_REQUEST: processCompareRequest( ( CompareRequest ) request, batchResponseDsml, monitor ); break; case DEL_REQUEST: processDelRequest( ( DeleteRequest ) request, batchResponseDsml, monitor ); break; case EXTENDED_REQUEST: processExtendedRequest( ( ExtendedRequest ) request, batchResponseDsml, monitor ); break; case MODIFY_REQUEST: processModifyRequest( ( ModifyRequest ) request, batchResponseDsml, monitor ); break; case MODIFYDN_REQUEST: processModifyDNRequest( ( ModifyDnRequest ) request, batchResponseDsml, monitor ); break; case SEARCH_REQUEST: processSearchRequest( ( SearchRequest ) request, batchResponseDsml, monitor ); break; default: throw new IllegalArgumentException( BrowserCoreMessages.dsml__should_not_be_encountering_request + request.getDecorated().getType() ); } } /** * Processes an bind request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processBindRequest( BindRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { BindResponseDsml authResponseDsml = new BindResponseDsml( codec ); LdapResult ldapResult = authResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( authResponseDsml ); } } /** * Processes an add request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processAddRequest( AddRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the add request Entry entry = request.getEntry(); browserConnection .getConnection() .getConnectionWrapper() .createEntry( entry.getDn().getName(), Utils.toAttributes( entry ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { AddResponseDsml addResponseDsml = new AddResponseDsml( codec ); LdapResult ldapResult = addResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); ldapResult.setMatchedDn( entry.getDn() ); batchResponseDsml.addResponse( addResponseDsml ); } // Update cached entries Dn dn = entry.getDn(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes a compare request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processCompareRequest( CompareRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { CompareResponseDsml compareResponseDsml = new CompareResponseDsml( codec ); LdapResult ldapResult = compareResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( compareResponseDsml ); } } /** * Processes a del request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processDelRequest( DeleteRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the del request browserConnection.getConnection().getConnectionWrapper() .deleteEntry( request.getName().getName(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { DelResponseDsml delResponseDsml = new DelResponseDsml( codec ); LdapResult ldapResult = delResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); delResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( delResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } } /** * Processes an extended request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processExtendedRequest( ExtendedRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // We can not support extended requests at the moment, // we need a more advanced connection wrapper. // Creating the response if ( batchResponseDsml != null ) { ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml( codec ); LdapResult ldapResult = extendedResponseDsml.getLdapResult(); ldapResult.setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM ); ldapResult.setDiagnosticMessage( BrowserCoreMessages.dsml__kind_request_not_supported ); batchResponseDsml.addResponse( extendedResponseDsml ); } } /** * Processes a modify request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyRequest( ModifyRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Creating the modification items List modificationItems = new ArrayList(); for ( Modification modification : request.getModifications() ) { modificationItems.add( new ModificationItem( convertModificationOperation( modification.getOperation() ), AttributeUtils.toJndiAttribute( modification.getAttribute() ) ) ); } // Executing the modify request browserConnection .getConnection() .getConnectionWrapper() .modifyEntry( request.getName().getName(), modificationItems.toArray( new ModificationItem[0] ), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml( codec ); LdapResult ldapResult = modifyResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modifyResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modifyResponseDsml ); } Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); if ( e != null ) { e.setAttributesInitialized( false ); } } /** * Converts the modification operation from Shared LDAP to JNDI * * @param operation * the Shared LDAP modification operation * @return * the equivalent modification operation in JNDI */ private int convertModificationOperation( ModificationOperation operation ) { switch ( operation ) { case ADD_ATTRIBUTE: return DirContext.ADD_ATTRIBUTE; case REMOVE_ATTRIBUTE: return DirContext.REMOVE_ATTRIBUTE; case REPLACE_ATTRIBUTE: return DirContext.REPLACE_ATTRIBUTE; default: return 0; } } /** * Processes a modify Dn request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) */ private void processModifyDNRequest( ModifyDnRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) { // Executing the modify Dn request browserConnection .getConnection() .getConnectionWrapper() .renameEntry( request.getName().getName(), request.getNewRdn().getName(), request.getDeleteOldRdn(), getControls( request ), monitor, null ); // Creating the response if ( batchResponseDsml != null ) { ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml( codec ); LdapResult ldapResult = modDNResponseDsml.getLdapResult(); setLdapResultValuesFromMonitor( ldapResult, monitor, MessageTypeEnum.ADD_REQUEST ); modDNResponseDsml.getLdapResult().setMatchedDn( request.getName() ); batchResponseDsml.addResponse( modDNResponseDsml ); } // Update cached entries Dn dn = request.getName(); IEntry e = browserConnection.getEntryFromCache( dn ); Dn parentDn = dn.getParent(); IEntry parentEntry = parentDn != null ? browserConnection.getEntryFromCache( parentDn ) : null; if ( e != null ) { e.setAttributesInitialized( false ); browserConnection.uncacheEntryRecursive( e ); } if ( parentEntry != null ) { parentEntry.setChildrenInitialized( false ); } if ( request.getNewSuperior() != null ) { Dn newSuperiorDn = request.getNewSuperior(); IEntry newSuperiorEntry = browserConnection.getEntryFromCache( newSuperiorDn ); if ( newSuperiorEntry != null ) { newSuperiorEntry.setChildrenInitialized( false ); } } } /** * Processes a search request. * * @param request * the request * @param batchResponseDsml * the DSML batch response (can be null) * @throws NamingException * @throws org.apache.directory.api.ldap.model.exception.LdapURLEncodingException * @throws org.apache.directory.api.ldap.model.exception.LdapException */ private void processSearchRequest( SearchRequest request, BatchResponseDsml batchResponseDsml, StudioProgressMonitor monitor ) throws NamingException, LdapURLEncodingException, LdapException { // Creating the response if ( batchResponseDsml != null ) { // [Optimization] We're only searching if we need to produce a response StudioNamingEnumeration ne = browserConnection .getConnection() .getConnectionWrapper() .search( request.getBase().getName(), request.getFilter().toString(), getSearchControls( request ), getAliasDereferencingMethod( request ), ReferralHandlingMethod.IGNORE, getControls( request ), monitor, null ); SearchParameter sp = new SearchParameter(); sp.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); ExportDsmlRunnable.processAsDsmlResponse( ne, batchResponseDsml, monitor, sp ); } } /** * Returns the {@link SearchControls} object associated with the request. * * @param request * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls( SearchRequest request ) { SearchControls controls = new SearchControls(); // Scope switch ( request.getScope() ) { case OBJECT: controls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: controls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } // Returning attributes List returningAttributes = new ArrayList(); for ( String attribute : request.getAttributes() ) { returningAttributes.add( attribute ); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if ( returningAttributes.size() == 0 ) { returningAttributes.add( "*" ); //$NON-NLS-1$ } controls.setReturningAttributes( returningAttributes.toArray( new String[0] ) ); // Size Limit controls.setCountLimit( request.getSizeLimit() ); // Time Limit controls.setTimeLimit( request.getTimeLimit() ); return controls; } /** * Returns the {@link AliasDereferencingMethod} object associated with the request. * * @param request * the search request * @return * the associated {@link AliasDereferencingMethod} object */ private AliasDereferencingMethod getAliasDereferencingMethod( SearchRequest request ) { switch ( request.getDerefAliases() ) { case NEVER_DEREF_ALIASES: return AliasDereferencingMethod.NEVER; case DEREF_ALWAYS: return AliasDereferencingMethod.ALWAYS; case DEREF_FINDING_BASE_OBJ: return AliasDereferencingMethod.FINDING; case DEREF_IN_SEARCHING: return AliasDereferencingMethod.SEARCH; default: return AliasDereferencingMethod.NEVER; } } private Control[] getControls( Message request ) { Collection controls = request.getControls().values(); if ( controls != null ) { List jndiControls = new ArrayList(); for ( org.apache.directory.api.ldap.model.message.Control control : controls ) { try { jndiControls.add( codec.toJndiControl( control ) ); } catch ( EncoderException e ) { throw new RuntimeException( e ); } } return jndiControls.toArray( new Control[jndiControls.size()] ); } return null; } /** * Get the LDAP Result corresponding to the given monitor * * @param monitor * the progress monitor * @return * the corresponding LDAP Result */ private void setLdapResultValuesFromMonitor( LdapResult ldapResult, StudioProgressMonitor monitor, MessageTypeEnum messageType ) { if ( !monitor.errorsReported() ) { ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); } else { // Getting the exception Throwable t = monitor.getException(); // Setting the result code ldapResult.setResultCode( ResultCodeEnum.getBestEstimate( t, messageType ) ); // Setting the error message if there's one if ( t.getMessage() != null ) { ldapResult.setDiagnosticMessage( t.getMessage() ); } } } }
blob  Long Method, 2 Data Class" } t f f . Long Method, 2. Data Class" } blob 0 3020 https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/ImportDsmlRunnable.java/#L94-L776 1 282 3020
1984  { "NO, I did not find any bad smell" : "Blob" , "Data Class" : [], "Feature Envy" : "YES I found bad smells", "the bad smells are" : [ "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage
blob   "Blob" , "Data Class" t f t   "Data Class"   0 12647 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 1 1984 12647
349 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MetadataProvider { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MetadataProvider.class); private static final String IN_FUNCTION = "in"; private static final String LIKE_FUNCTION = "like"; private static final String AND_FUNCTION = "booleanand"; private static final String OR_FUNCTION = "booleanor"; /** * @return Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ public static Runnable catalogs(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { return new CatalogsProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the schema metadata for given {@link GetSchemasReq} and sends response at the end. */ public static Runnable schemas(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { return new SchemasProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the table metadata for given {@link GetTablesReq} and sends response at the end. */ public static Runnable tables(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { return new TablesProvider(session, dContext, req, responseSender); } /** * @return Runnable that fetches the column metadata for given {@link GetColumnsReq} and sends response at the end. */ public static Runnable columns(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { return new ColumnsProvider(session, dContext, req, responseSender); } /** * Super class for all metadata provider runnable classes. */ private abstract static class MetadataRunnable implements Runnable { protected final UserSession session; private final ResponseSender responseSender; private final DrillbitContext dContext; private MetadataRunnable(final UserSession session, final DrillbitContext dContext, final ResponseSender responseSender) { this.session = Preconditions.checkNotNull(session); this.dContext = Preconditions.checkNotNull(dContext); this.responseSender = Preconditions.checkNotNull(responseSender); } @Override public void run() { try(SchemaTreeProvider schemaTreeProvider = new SchemaTreeProvider(dContext)) { responseSender.send(runInternal(session, schemaTreeProvider)); } catch (final Throwable error) { logger.error("Unhandled metadata provider error", error); } } /** * @return A {@link Response} message. Response must be returned in any case. */ protected abstract Response runInternal(UserSession session, SchemaTreeProvider schemaProvider); public DrillConfig getConfig() { return dContext.getConfig(); } } /** * Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end. */ private static class CatalogsProvider extends MetadataRunnable { private static final Ordering CATALOGS_ORDERING = new Ordering() { @Override public int compare(CatalogMetadata left, CatalogMetadata right) { return Ordering.natural().compare(left.getCatalogName(), right.getCatalogName()); } }; private final GetCatalogsReq req; public CatalogsProvider(final UserSession session, final DrillbitContext dContext, final GetCatalogsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetCatalogsResp.Builder respBuilder = GetCatalogsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(CATALOGS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Catalog c : records) { final CatalogMetadata.Builder catBuilder = CatalogMetadata.newBuilder(); catBuilder.setCatalogName(c.CATALOG_NAME); catBuilder.setDescription(c.CATALOG_DESCRIPTION); catBuilder.setConnect(c.CATALOG_CONNECT); metadata.add(catBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, CATALOGS_ORDERING); respBuilder.addAllCatalogs(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get catalogs", e)); } finally { return new Response(RpcType.CATALOGS, respBuilder.build()); } } } private static class SchemasProvider extends MetadataRunnable { private static final Ordering SCHEMAS_ORDERING = new Ordering() { @Override public int compare(SchemaMetadata left, SchemaMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .result(); }; }; private final GetSchemasReq req; private SchemasProvider(final UserSession session, final DrillbitContext dContext, final GetSchemasReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetSchemasResp.Builder respBuilder = GetSchemasResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, null, null, null); try { final PojoRecordReader records = getPojoRecordReader(SCHEMATA, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Schema s : records) { final SchemaMetadata.Builder schemaBuilder = SchemaMetadata.newBuilder(); schemaBuilder.setCatalogName(s.CATALOG_NAME); schemaBuilder.setSchemaName(s.SCHEMA_NAME); schemaBuilder.setOwner(s.SCHEMA_OWNER); schemaBuilder.setType(s.TYPE); schemaBuilder.setMutable(s.IS_MUTABLE); metadata.add(schemaBuilder.build()); } // Reorder results according to JDBC spec Collections.sort(metadata, SCHEMAS_ORDERING); respBuilder.addAllSchemas(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get schemas", e)); } finally { return new Response(RpcType.SCHEMAS, respBuilder.build()); } } } private static class TablesProvider extends MetadataRunnable { private static final Ordering TABLES_ORDERING = new Ordering() { @Override public int compare(TableMetadata left, TableMetadata right) { return ComparisonChain.start() .compare(left.getType(), right.getType()) .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .result(); } }; private final GetTablesReq req; private TablesProvider(final UserSession session, final DrillbitContext dContext, final GetTablesReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, req.getTableTypeFilterCount() != 0 ? req.getTableTypeFilterList() : null, null); try { final PojoRecordReader records = getPojoRecordReader(TABLES, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Table t : records) { final TableMetadata.Builder tableBuilder = TableMetadata.newBuilder(); tableBuilder.setCatalogName(t.TABLE_CATALOG); tableBuilder.setSchemaName(t.TABLE_SCHEMA); tableBuilder.setTableName(t.TABLE_NAME); tableBuilder.setType(t.TABLE_TYPE); metadata.add(tableBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, TABLES_ORDERING); respBuilder.addAllTables(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get tables", e)); } finally { return new Response(RpcType.TABLES, respBuilder.build()); } } } private static class ColumnsProvider extends MetadataRunnable { private static final Ordering COLUMNS_ORDERING = new Ordering() { @Override public int compare(ColumnMetadata left, ColumnMetadata right) { return ComparisonChain.start() .compare(left.getCatalogName(), right.getCatalogName()) .compare(left.getSchemaName(), right.getSchemaName()) .compare(left.getTableName(), right.getTableName()) .compare(left.getOrdinalPosition(), right.getOrdinalPosition()) .result(); } }; private final GetColumnsReq req; private ColumnsProvider(final UserSession session, final DrillbitContext dContext, final GetColumnsReq req, final ResponseSender responseSender) { super(session, dContext, responseSender); this.req = Preconditions.checkNotNull(req); } @Override protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) { final GetColumnsResp.Builder respBuilder = GetColumnsResp.newBuilder(); final InfoSchemaFilter filter = createInfoSchemaFilter( req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null, req.hasTableNameFilter() ? req.getTableNameFilter() : null, null, req.hasColumnNameFilter() ? req.getColumnNameFilter() : null ); try { final PojoRecordReader records = getPojoRecordReader(COLUMNS, filter, getConfig(), schemaProvider, session); List metadata = new ArrayList<>(); for(Column c : records) { final ColumnMetadata.Builder columnBuilder = ColumnMetadata.newBuilder(); columnBuilder.setCatalogName(c.TABLE_CATALOG); columnBuilder.setSchemaName(c.TABLE_SCHEMA); columnBuilder.setTableName(c.TABLE_NAME); columnBuilder.setColumnName(c.COLUMN_NAME); columnBuilder.setOrdinalPosition(c.ORDINAL_POSITION); if (c.COLUMN_DEFAULT != null) { columnBuilder.setDefaultValue(c.COLUMN_DEFAULT); } if ("YES".equalsIgnoreCase(c.IS_NULLABLE)) { columnBuilder.setIsNullable(true); } else { columnBuilder.setIsNullable(false); } columnBuilder.setDataType(c.DATA_TYPE); if (c.CHARACTER_MAXIMUM_LENGTH != null) { columnBuilder.setCharMaxLength(c.CHARACTER_MAXIMUM_LENGTH); } if (c.CHARACTER_OCTET_LENGTH != null) { columnBuilder.setCharOctetLength(c.CHARACTER_OCTET_LENGTH); } if (c.NUMERIC_SCALE != null) { columnBuilder.setNumericScale(c.NUMERIC_SCALE); } if (c.NUMERIC_PRECISION != null) { columnBuilder.setNumericPrecision(c.NUMERIC_PRECISION); } if (c.NUMERIC_PRECISION_RADIX != null) { columnBuilder.setNumericPrecisionRadix(c.NUMERIC_PRECISION_RADIX); } if (c.DATETIME_PRECISION != null) { columnBuilder.setDateTimePrecision(c.DATETIME_PRECISION); } if (c.INTERVAL_TYPE != null) { columnBuilder.setIntervalType(c.INTERVAL_TYPE); } if (c.INTERVAL_PRECISION != null) { columnBuilder.setIntervalPrecision(c.INTERVAL_PRECISION); } if (c.COLUMN_SIZE != null) { columnBuilder.setColumnSize(c.COLUMN_SIZE); } metadata.add(columnBuilder.build()); } // Reorder results according to JDBC/ODBC spec Collections.sort(metadata, COLUMNS_ORDERING); respBuilder.addAllColumns(metadata); respBuilder.setStatus(RequestStatus.OK); } catch (Throwable e) { respBuilder.setStatus(RequestStatus.FAILED); respBuilder.setError(createPBError("get columns", e)); } finally { return new Response(RpcType.COLUMNS, respBuilder.build()); } } } /** * Helper method to create a {@link InfoSchemaFilter} that combines the given filters with an AND. * * @param catalogNameFilter Optional filter on catalog name * @param schemaNameFilter Optional filter on schema name * @param tableNameFilter Optional filter on table name * @param tableTypeFilter Optional filter on table type * @param columnNameFilter Optional filter on column name * @return information schema filter */ private static InfoSchemaFilter createInfoSchemaFilter(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, List tableTypeFilter, LikeFilter columnNameFilter) { FunctionExprNode exprNode = createLikeFunctionExprNode(CATS_COL_CATALOG_NAME, catalogNameFilter); // schema names are case insensitive in Drill and stored in lower case // convert like filter condition elements to lower case if (schemaNameFilter != null) { LikeFilter.Builder builder = LikeFilter.newBuilder(); if (schemaNameFilter.hasPattern()) { builder.setPattern(schemaNameFilter.getPattern().toLowerCase()); } if (schemaNameFilter.hasEscape()) { builder.setEscape(schemaNameFilter.getEscape().toLowerCase()); } schemaNameFilter = builder.build(); } exprNode = combineFunctions(AND_FUNCTION, exprNode, combineFunctions(OR_FUNCTION, createLikeFunctionExprNode(SHRD_COL_TABLE_SCHEMA, schemaNameFilter), createLikeFunctionExprNode(SCHS_COL_SCHEMA_NAME, schemaNameFilter) ) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(SHRD_COL_TABLE_NAME, tableNameFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createInFunctionExprNode(TBLS_COL_TABLE_TYPE, tableTypeFilter) ); exprNode = combineFunctions(AND_FUNCTION, exprNode, createLikeFunctionExprNode(COLS_COL_COLUMN_NAME, columnNameFilter) ); return exprNode != null ? new InfoSchemaFilter(exprNode) : null; } /** * Helper method to create {@link FunctionExprNode} from {@link LikeFilter}. * @param fieldName Name of the filed on which the like expression is applied. * @param likeFilter * @return {@link FunctionExprNode} for given arguments. Null if the likeFilter is null. */ private static FunctionExprNode createLikeFunctionExprNode(String fieldName, LikeFilter likeFilter) { if (likeFilter == null) { return null; } return new FunctionExprNode(LIKE_FUNCTION, likeFilter.hasEscape() ? ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern()), new ConstantExprNode(likeFilter.getEscape())) : ImmutableList.of( new FieldExprNode(fieldName), new ConstantExprNode(likeFilter.getPattern())) ); } /** * Helper method to create {@link FunctionExprNode} from {@code List}. * @param fieldName Name of the filed on which the like expression is applied. * @param valuesFilter a list of values * @return {@link FunctionExprNode} for given arguments. Null if the valuesFilter is null. */ private static FunctionExprNode createInFunctionExprNode(String fieldName, List valuesFilter) { if (valuesFilter == null) { return null; } ImmutableList.Builder nodes = ImmutableList.builder(); nodes.add(new FieldExprNode(fieldName)); for(String type: valuesFilter) { nodes.add(new ConstantExprNode(type)); } return new FunctionExprNode(IN_FUNCTION, nodes.build()); } /** * Helper method to combine two {@link FunctionExprNode}s with a given functionName. If one of them is * null, other one is returned as it is. */ private static FunctionExprNode combineFunctions(final String functionName, final FunctionExprNode func1, final FunctionExprNode func2) { if (func1 == null) { return func2; } if (func2 == null) { return func1; } return new FunctionExprNode(functionName, ImmutableList.of(func1, func2)); } /** * Helper method to create a {@link PojoRecordReader} for given arguments. * @param tableType * @param filter * @param provider * @param userSession * @return */ private static PojoRecordReader getPojoRecordReader(final InfoSchemaTableType tableType, final InfoSchemaFilter filter, final DrillConfig config, final SchemaTreeProvider provider, final UserSession userSession) { final SchemaPlus rootSchema = provider.createFullRootSchema(userSession.getCredentials().getUserName(), newSchemaConfigInfoProvider(config, userSession, provider)); return tableType.getRecordReader(rootSchema, filter, userSession.getOptions()); } /** * Helper method to create a {@link SchemaConfigInfoProvider} instance for metadata purposes. * @param session * @param schemaTreeProvider * @return */ private static SchemaConfigInfoProvider newSchemaConfigInfoProvider(final DrillConfig config, final UserSession session, final SchemaTreeProvider schemaTreeProvider) { return new SchemaConfigInfoProvider() { private final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(config, this); @Override public ViewExpansionContext getViewExpansionContext() { return viewExpansionContext; } @Override public SchemaPlus getRootSchema(String userName) { return schemaTreeProvider.createRootSchema(userName, this); } @Override public OptionValue getOption(String optionKey) { return session.getOptions().getOption(optionKey); } @Override public String getQueryUserName() { return session.getCredentials().getUserName(); } }; } /** * Helper method to create {@link DrillPBError} for client response message. * @param failedFunction Brief description of the failed function. * @param ex Exception thrown * @return */ static DrillPBError createPBError(final String failedFunction, final Throwable ex) { final String errorId = UUID.randomUUID().toString(); logger.error("Failed to {}. ErrorId: {}", failedFunction, errorId, ex); final DrillPBError.Builder builder = DrillPBError.newBuilder(); builder.setErrorType(ErrorType.SYSTEM); // Metadata requests shouldn't cause any user errors builder.setErrorId(errorId); if (ex.getMessage() != null) { builder.setMessage(ex.getMessage()); } builder.setException(ErrorHelper.getWrapper(ex)); return builder.build(); } }
blob data class t t f data class blob 0 3592 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/work/metadata/MetadataProvider.java/#L84-L621 1 349 3592
1746       { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); }
long method Long Method, Data Class t f t  Data Class   0 11853 https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 1 1746 11853
860 {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ConnectionLoadBalanceServer { private static final Logger logger = LoggerFactory.getLogger(ConnectionLoadBalanceServer.class); private final String hostname; private final int port; private final SSLContext sslContext; private final ExecutorService threadPool; private final LoadBalanceProtocol loadBalanceProtocol; private final int connectionTimeoutMillis; private final int numThreads; private final EventReporter eventReporter; private volatile Set communicationActions = Collections.emptySet(); private final BlockingQueue connectionQueue = new LinkedBlockingQueue<>(); private volatile AcceptConnection acceptConnection; private volatile ServerSocket serverSocket; private volatile boolean stopped = true; public ConnectionLoadBalanceServer(final String hostname, final int port, final SSLContext sslContext, final int numThreads, final LoadBalanceProtocol loadBalanceProtocol, final EventReporter eventReporter, final int connectionTimeoutMillis) { this.hostname = hostname; this.port = port; this.sslContext = sslContext; this.loadBalanceProtocol = loadBalanceProtocol; this.connectionTimeoutMillis = connectionTimeoutMillis; this.numThreads = numThreads; this.eventReporter = eventReporter; threadPool = new FlowEngine(numThreads, "Load Balance Server"); } public void start() throws IOException { if (!stopped) { return; } stopped = false; if (serverSocket != null) { return; } try { serverSocket = createServerSocket(); } catch (final Exception e) { throw new IOException("Could not begin listening for incoming connections in order to load balance data across the cluster. Please verify the values of the " + "'nifi.cluster.load.balance.port' and 'nifi.cluster.load.balance.host' properties as well as the 'nifi.security.*' properties", e); } final Set actions = new HashSet<>(numThreads); for (int i=0; i < numThreads; i++) { final CommunicateAction action = new CommunicateAction(loadBalanceProtocol); actions.add(action); threadPool.submit(action); } this.communicationActions = actions; acceptConnection = new AcceptConnection(serverSocket); final Thread receiveConnectionThread = new Thread(acceptConnection); receiveConnectionThread.setName("Receive Queue Load-Balancing Connections"); receiveConnectionThread.start(); } public int getPort() { return serverSocket.getLocalPort(); } public void stop() { stopped = false; threadPool.shutdown(); if (acceptConnection != null) { acceptConnection.stop(); } communicationActions.forEach(CommunicateAction::stop); Socket socket; while ((socket = connectionQueue.poll()) != null) { try { socket.close(); logger.info("{} Closed connection to {} on Server stop", this, socket.getRemoteSocketAddress()); } catch (final IOException ioe) { logger.warn("Failed to properly close socket to " + socket.getRemoteSocketAddress(), ioe); } } } private ServerSocket createServerSocket() throws IOException { final InetAddress inetAddress = hostname == null ? null : InetAddress.getByName(hostname); if (sslContext == null) { return new ServerSocket(port, 50, InetAddress.getByName(hostname)); } else { final ServerSocket serverSocket = sslContext.getServerSocketFactory().createServerSocket(port, 50, inetAddress); ((SSLServerSocket) serverSocket).setNeedClientAuth(true); return serverSocket; } } private class CommunicateAction implements Runnable { private final LoadBalanceProtocol loadBalanceProtocol; private volatile boolean stopped = false; public CommunicateAction(final LoadBalanceProtocol loadBalanceProtocol) { this.loadBalanceProtocol = loadBalanceProtocol; } public void stop() { this.stopped = true; } @Override public void run() { String peerDescription = ""; while (!stopped) { Socket socket = null; try { socket = connectionQueue.poll(1, TimeUnit.SECONDS); if (socket == null) { continue; } peerDescription = socket.getRemoteSocketAddress().toString(); if (socket.isClosed()) { logger.debug("Connection to Peer {} is closed. Will not attempt to communicate over this Socket.", peerDescription); continue; } logger.debug("Receiving FlowFiles from Peer {}", peerDescription); loadBalanceProtocol.receiveFlowFiles(socket); if (socket.isConnected()) { logger.debug("Finished receiving FlowFiles from Peer {}. Will recycle connection.", peerDescription); connectionQueue.offer(socket); } else { logger.debug("Finished receiving FlowFiles from Peer {}. Socket is no longer connected so will not recycle connection.", peerDescription); } } catch (final Exception e) { if (socket != null) { try { socket.close(); } catch (final IOException ioe) { e.addSuppressed(ioe); } } logger.error("Failed to communicate with Peer {}", peerDescription, e); eventReporter.reportEvent(Severity.ERROR, "Load Balanced Connection", "Failed to receive FlowFiles for Load Balancing due to " + e); } } logger.info("Connection Load Balance Server shutdown. Will no longer handle incoming requests."); } } private class AcceptConnection implements Runnable { private final ServerSocket serverSocket; private volatile boolean stopped = false; public AcceptConnection(final ServerSocket serverSocket) { this.serverSocket = serverSocket; } public void stop() { stopped = true; } @Override public void run() { try { serverSocket.setSoTimeout(1000); } catch (final Exception e) { logger.error("Failed to set soTimeout on Server Socket for Load Balancing data across cluster", e); } while (!stopped) { try { final Socket socket; try { socket = serverSocket.accept(); } catch (final SocketTimeoutException ste) { continue; } socket.setSoTimeout(connectionTimeoutMillis); connectionQueue.offer(socket); } catch (final Exception e) { logger.error("{} Failed to accept connection from other node in cluster", ConnectionLoadBalanceServer.this, e); } } try { serverSocket.close(); } catch (final Exception e) { logger.warn("Failed to properly shutdown Server Socket for Load Balancing", e); } } } @Override public String toString() { return "ConnectionLoadBalanceServer[hostname=" + hostname + ", port=" + port + ", secure=" + (sslContext != null) + "]"; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 7901 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/clustered/server/ConnectionLoadBalanceServer.java/#L42-L251 1 860 7901
1690  {"response": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } }
blob data class, long method t t f data class, long method blob 0 11702 https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 1 1690 11702
1339      { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class DFA28 extends DFA { public DFA28(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 28; this.eot = dfa_9; this.eof = dfa_21; this.min = dfa_10; this.max = dfa_11; this.accept = dfa_12; this.special = dfa_13; this.transition = dfa_14; } public String getDescription() { return "4005:2: ( rule__Object__UnorderedGroup_5__5 )?"; } public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_0 = input.LA(1); int index28_0 = input.index(); input.rewind(); s = -1; if ( LA28_0 == 19 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 0) ) {s = 1;} else if ( LA28_0 == 20 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 1) ) {s = 2;} else if ( LA28_0 == 21 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 2) ) {s = 3;} else if ( LA28_0 == 33 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 3) ) {s = 4;} else if ( LA28_0 == 26 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 5;} else if ( LA28_0 == 27 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 4) ) {s = 6;} else if ( LA28_0 == 22 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 5) ) {s = 7;} else if ( LA28_0 == 24 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 6) ) {s = 8;} else if ( LA28_0 == 25 && getUnorderedGroupHelper().canSelect(grammarAccess.getObjectAccess().getUnorderedGroup_5(), 7) ) {s = 9;} else if ( (LA28_0==EOF||LA28_0==17) ) {s = 10;} input.seek(index28_0); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; } }
blob long method, data class t t f long method, data class blob 0 10738 https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/ide/contentassist/antlr/internal/InternalBug304681TestLanguageParser.java/#L20062-L20120 1 1339 10738
245   { "message": "YES I found bad smells", "bad smells are": [ "1. Data Class", "2. Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } }
blob 1. data class, 2. long method t t f 1. data class, 2. long method blob 0 2653 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 1 245 2653
4965 {"answer": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } }
blob data class, long method t t f data class, long method blob 0 13592 https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 1 4965 13592
27  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl
blob long method, data class t t f long method, data class blob 0 704 https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 1 27 704
2388      {"message": "YES I found bad smells. The bad smells are: Blob, Data Class, Long Method"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } }
feature envy blob, data class, long method t t f blob, data class, long method feature envy 0 14352 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 1 2388 14352
1741 YES I found bad smells the bad smells are: 1. Duplication 2. Long method 3. Feature envy 4. Inappropriate intimacy 5. Lazy class 6. Data class 7. Switch statement 8. Primitive obsession 9. Magic number 10. Long parameter list 11. Incomplete library class 12. Shotgun surgery (methods referencing multiple variables outside of their own class) 13. Dead code (unused methods) 14. Violation of the single responsibility principle (multiple methods handling different responsibilities) 15. Inconsistent naming and spacing conventions 16. Inefficient use of comments 17. Lack of exception handling 18. Inconsistent use of data types (mixing int and double without clear reason) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class GraphicsNodeRable8Bit extends AbstractRable implements GraphicsNodeRable, PaintRable { private AffineTransform cachedGn2dev = null; private AffineTransform cachedUsr2dev = null; private CachableRed cachedRed = null; private Rectangle2D cachedBounds = null; /** * Should GraphicsNodeRable call primitivePaint or Paint. */ private boolean usePrimitivePaint = true; /** * Returns true if this Rable get's it's contents by calling * primitivePaint on the associated GraphicsNode or * false if it uses paint. */ public boolean getUsePrimitivePaint() { return usePrimitivePaint; } /** * Set to true if this Rable should get it's contents by calling * primitivePaint on the associated GraphicsNode or false * if it should use paint. */ public void setUsePrimitivePaint(boolean usePrimitivePaint) { this.usePrimitivePaint = usePrimitivePaint; } /** * GraphicsNode this image can render */ private GraphicsNode node; /** * Returns the GraphicsNode rendered by this image */ public GraphicsNode getGraphicsNode(){ return node; } /** * Sets the GraphicsNode this image should render */ public void setGraphicsNode(GraphicsNode node){ if(node == null){ throw new IllegalArgumentException(); } this.node = node; } /** * Clear any cached Red. */ public void clearCache() { cachedRed = null; cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; } /** * @param node The GraphicsNode this image should represent */ public GraphicsNodeRable8Bit(GraphicsNode node){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node The GraphicsNode this image should represent * @param props The Properties for this image. */ public GraphicsNodeRable8Bit(GraphicsNode node, Map props){ super((Filter)null, props); if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = true; } /** * @param node the GraphicsNode this image should represent * @param usePrimitivePaint indicates if the image should * include any filters or mask operations on node */ public GraphicsNodeRable8Bit(GraphicsNode node, boolean usePrimitivePaint){ if(node == null) throw new IllegalArgumentException(); this.node = node; this.usePrimitivePaint = usePrimitivePaint; } /** * Returns the bounds of this Rable in the user coordinate system. */ public Rectangle2D getBounds2D(){ if (usePrimitivePaint){ Rectangle2D primitiveBounds = node.getPrimitiveBounds(); if(primitiveBounds == null) return new Rectangle2D.Double(0, 0, 0, 0); return (Rectangle2D)(primitiveBounds.clone()); } // When not using Primitive paint we return out bounds in our // parent's user space. This makes sense since this is the // space that we will draw our selves into (since paint unlike // primitivePaint incorporates the transform from our user // space to our parents user space). Rectangle2D bounds = node.getBounds(); if(bounds == null){ return new Rectangle2D.Double(0, 0, 0, 0); } AffineTransform at = node.getTransform(); if (at != null){ bounds = at.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns true if successive renderings (that is, calls to * createRendering() or createScaledRendering()) with the same arguments * may produce different results. This method may be used to * determine whether an existing rendering may be cached and * reused. It is always safe to return true. */ public boolean isDynamic(){ return false; } /** * Should perform the equivilent action as * createRendering followed by drawing the RenderedImage to * Graphics2D, or return false. * * @param g2d The Graphics2D to draw to. * @return true if the paint call succeeded, false if * for some reason the paint failed (in which * case a createRendering should be used). */ public boolean paintRable(Graphics2D g2d) { // This optimization only apply if we are using // SrcOver. Otherwise things break... Composite c = g2d.getComposite(); if (!SVGComposite.OVER.equals(c)) return false; ColorSpace g2dCS = GraphicsUtil.getDestinationColorSpace(g2d); if ((g2dCS == null) || (g2dCS != ColorSpace.getInstance(ColorSpace.CS_sRGB))){ // Only draw directly into sRGB destinations... return false; } // System.out.println("drawImage GNR: " + g2dCS); GraphicsNode gn = getGraphicsNode(); if (getUsePrimitivePaint()){ gn.primitivePaint(g2d); } else{ gn.paint(g2d); } // Paint did the work... return true; } /** * Creates a RenderedImage that represented a rendering of this image * using a given RenderContext. This is the most general way to obtain a * rendering of a RenderableImage. * * The created RenderedImage may have a property identified * by the String HINTS_OBSERVED to indicate which RenderingHints * (from the RenderContext) were used to create the image. * In addition any RenderedImages * that are obtained via the getSources() method on the created * RenderedImage may have such a property. * * @param renderContext the RenderContext to use to produce the rendering. * @return a RenderedImage containing the rendered data. */ public RenderedImage createRendering(RenderContext renderContext){ // Get user space to device space transform AffineTransform usr2dev = renderContext.getTransform(); AffineTransform gn2dev; if (usr2dev == null) { usr2dev = new AffineTransform(); gn2dev = usr2dev; } else { gn2dev = (AffineTransform)usr2dev.clone(); } // Get the nodes transform (so we can pick up changes in this. AffineTransform gn2usr = node.getTransform(); if (gn2usr != null) { gn2dev.concatenate(gn2usr); } Rectangle2D bounds2D = getBounds2D(); if ((cachedBounds != null) && (cachedGn2dev != null) && (cachedBounds.equals(bounds2D)) && (gn2dev.getScaleX() == cachedGn2dev.getScaleX()) && (gn2dev.getScaleY() == cachedGn2dev.getScaleY()) && (gn2dev.getShearX() == cachedGn2dev.getShearX()) && (gn2dev.getShearY() == cachedGn2dev.getShearY())) { // Just some form of Translation double deltaX = (usr2dev.getTranslateX() - cachedUsr2dev.getTranslateX()); double deltaY = (usr2dev.getTranslateY() - cachedUsr2dev.getTranslateY()); // System.out.println("Using Cached Red!!! " + // deltaX + "x" + deltaY); if ((deltaX ==0) && (deltaY == 0)) // Actually no translation return cachedRed; // System.out.println("Delta: [" + deltaX + ", " + deltaY + "]"); // Integer translation in device space.. if ((deltaX == (int)deltaX) && (deltaY == (int)deltaY)) { return new TranslateRed (cachedRed, (int)Math.round(cachedRed.getMinX()+deltaX), (int)Math.round(cachedRed.getMinY()+deltaY)); } } // Fell through let's do a new rendering... if (false) { System.out.println("Not using Cached Red: " + usr2dev); System.out.println("Old: " + cachedUsr2dev); } if((bounds2D.getWidth() > 0) && (bounds2D.getHeight() > 0)) { cachedUsr2dev = (AffineTransform)usr2dev.clone(); cachedGn2dev = gn2dev; cachedBounds = bounds2D; cachedRed = new GraphicsNodeRed8Bit (node, usr2dev, usePrimitivePaint, renderContext.getRenderingHints()); return cachedRed; } cachedUsr2dev = null; cachedGn2dev = null; cachedBounds = null; cachedRed = null; return null; } }
blob  Duplication2 Long method3 Feature envy4 Inappropriate intimacy5 Lazy class6 Data class7 Switch statement8 Primitive obsession9 Magic number t f f . Duplication2. Long method3. Feature envy4. Inappropriate intimacy5. Lazy class6. Data class7. Switch statement8. Primitive obsession9. Magic number blob 0 11842 https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-gvt/src/main/java/org/apache/batik/gvt/filter/GraphicsNodeRable8Bit.java/#L47-L318 2 1741 11842
5561   YES I found bad smells the bad smells are listed in this format: 1. Long method, 2. Data class, 3. Feature envy The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
} private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true;
long method  Long method, 2 Data class, 3 Feature envy t f t  2. Data class, 3. Feature envy   0 7769 https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 1 5561 7769
1393     { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void setup(Http2SolrClient http2Client) { HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore(); authenticationStore.addAuthentication(createSPNEGOAuthentication()); http2Client.getHttpClient().setAuthenticationStore(authenticationStore); http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient())); }
feature envy long method, data class t t f long method, data class feature envy 0 10847 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java/#L124-L130 1 1393 10847
854  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } }
blob data class t t f data class blob 0 7878 https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 1 854 7878
819       { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Primitive obsession", "Feature envy", "Long parameter list", "Data clumps", "Data class", "Duplicate code", "Inappropriate intimacy" ] } I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
@SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } }
blob long method, primitive obsession, feature envy, long parameter list, data clumps, data class, duplicate code, inappropriate intimacy t t f long method, primitive obsession, feature envy, long parameter list, data clumps, data class, duplicate code, inappropriate intimacy blob 0 7677 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 2 819 7677
638  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } }
blob long method, data class t t f long method, data class blob 0 6319 https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 1 638 6319
219      { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PTransformReplacements { /** * Gets the singleton input of an {@link AppliedPTransform}, ignoring any additional inputs * returned by {@link PTransform#getAdditionalInputs()}. */ public static PCollection getSingletonMainInput( AppliedPTransform, ?, ?> application) { return getSingletonMainInput( application.getInputs(), application.getTransform().getAdditionalInputs().keySet()); } private static PCollection getSingletonMainInput( Map, PValue> inputs, Set> ignoredTags) { PCollection mainInput = null; for (Map.Entry, PValue> input : inputs.entrySet()) { if (!ignoredTags.contains(input.getKey())) { checkArgument( mainInput == null, "Got multiple inputs that are not additional inputs for a " + "singleton main input: %s and %s", mainInput, input.getValue()); checkArgument( input.getValue() instanceof PCollection, "Unexpected input type %s", input.getValue().getClass()); mainInput = (PCollection) input.getValue(); } } checkArgument( mainInput != null, "No main input found in inputs: Inputs %s, Side Input tags %s", inputs, ignoredTags); return mainInput; } public static PCollection getSingletonMainOutput( AppliedPTransform, ? extends PTransform>> transform) { return (PCollection) Iterables.getOnlyElement(transform.getOutputs().values()); } }
blob 1: data class, 2: long method t t f 1: data class, 2: long method blob 0 2390 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformReplacements.java/#L32-L73 1 219 2390
1264 { "result": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@VisibleForTesting static class LogStream implements org.apache.aurora.scheduler.log.Log.Stream { @VisibleForTesting static final class OpStats { private final String opName; private final SlidingStats timing; private final AtomicLong timeouts; private final AtomicLong failures; OpStats(String opName) { this.opName = MorePreconditions.checkNotBlank(opName); timing = new SlidingStats("scheduler_log_native_" + opName, "nanos"); timeouts = exportLongStat("scheduler_log_native_%s_timeouts", opName); failures = exportLongStat("scheduler_log_native_%s_failures", opName); } private static AtomicLong exportLongStat(String template, Object... args) { return Stats.exportLong(String.format(template, args)); } } private static final Function MESOS_ENTRY_TO_ENTRY = LogEntry::new; private final OpStats readStats = new OpStats("read"); private final OpStats appendStats = new OpStats("append"); private final OpStats truncateStats = new OpStats("truncate"); private final AtomicLong entriesSkipped = Stats.exportLong("scheduler_log_native_native_entries_skipped"); private final LogInterface log; private final ReaderInterface reader; private final long readTimeout; private final TimeUnit readTimeUnit; private final Provider writerFactory; private final long writeTimeout; private final TimeUnit writeTimeUnit; private final byte[] noopEntry; private final Lifecycle lifecycle; /** * The underlying writer to use for mutation operations. This field has three states: * * present: the writer is active and available for use * absent: the writer has not yet been initialized (initialization is lazy) * {@code null}: the writer has suffered a fatal error and no further operations may * be performed. * * When {@code true}, indicates that the log has suffered a fatal error and no further * operations may be performed. */ @Nullable private Optional writer = Optional.empty(); LogStream( LogInterface log, ReaderInterface reader, Amount readTimeout, Provider writerFactory, Amount writeTimeout, byte[] noopEntry, Lifecycle lifecycle) { this.log = log; this.reader = reader; this.readTimeout = readTimeout.getValue(); this.readTimeUnit = readTimeout.getUnit().getTimeUnit(); this.writerFactory = writerFactory; this.writeTimeout = writeTimeout.getValue(); this.writeTimeUnit = writeTimeout.getUnit().getTimeUnit(); this.noopEntry = noopEntry; this.lifecycle = lifecycle; } @Override public Iterator readAll() throws StreamAccessException { // TODO(John Sirois): Currently we must be the coordinator to ensure we get the 'full read' // of log entries expected by the users of the org.apache.aurora.scheduler.log.Log interface. // Switch to another method of ensuring this when it becomes available in mesos' log // interface. try { append(noopEntry); } catch (StreamAccessException e) { throw new StreamAccessException("Error writing noop prior to a read", e); } final Log.Position from = reader.beginning(); final Log.Position to = end().unwrap(); // Reading all the entries at once may cause large garbage collections. Instead, we // lazily read the entries one by one as they are requested. // TODO(Benjamin Hindman): Eventually replace this functionality with functionality // from the Mesos Log. return new UnmodifiableIterator() { private long position = Longs.fromByteArray(from.identity()); private final long endPosition = Longs.fromByteArray(to.identity()); private Entry entry = null; @Override public boolean hasNext() { if (entry != null) { return true; } while (position <= endPosition) { long start = System.nanoTime(); try { Log.Position p = log.position(Longs.toByteArray(position)); LOG.debug("Reading position {} from the log", position); List entries = reader.read(p, p, readTimeout, readTimeUnit); // N.B. HACK! There is currently no way to "increment" a position. Until the Mesos // Log actually provides a way to "stream" the log, we approximate as much by // using longs via Log.Position.identity and Log.position. position++; // Reading positions in this way means it's possible that we get an "invalid" entry // (e.g., in the underlying log terminology this would be anything but an append) // which will be removed from the returned entries resulting in an empty list. // We skip these. if (entries.isEmpty()) { entriesSkipped.getAndIncrement(); } else { entry = MESOS_ENTRY_TO_ENTRY.apply(Iterables.getOnlyElement(entries)); return true; } } catch (TimeoutException e) { readStats.timeouts.getAndIncrement(); throw new StreamAccessException("Timeout reading from log.", e); } catch (Log.OperationFailedException e) { readStats.failures.getAndIncrement(); throw new StreamAccessException("Problem reading from log", e); } finally { readStats.timing.accumulate(System.nanoTime() - start); } } return false; } @Override public Entry next() { if (entry == null && !hasNext()) { throw new NoSuchElementException(); } Entry result = requireNonNull(entry); entry = null; return result; } }; } @Override public LogPosition append(final byte[] contents) throws StreamAccessException { requireNonNull(contents); Log.Position position = mutate( appendStats, logWriter -> logWriter.append(contents, writeTimeout, writeTimeUnit)); return LogPosition.wrap(position); } @Timed("scheduler_log_native_truncate_before") @Override public void truncateBefore(org.apache.aurora.scheduler.log.Log.Position position) throws StreamAccessException { Preconditions.checkArgument(position instanceof LogPosition); final Log.Position before = ((LogPosition) position).unwrap(); mutate(truncateStats, logWriter -> { logWriter.truncate(before, writeTimeout, writeTimeUnit); return null; }); } private interface Mutation { T apply(WriterInterface writer) throws TimeoutException, Log.WriterFailedException; } private StreamAccessException disableLog(AtomicLong stat, String message, Throwable cause) { stat.incrementAndGet(); writer = null; lifecycle.shutdown(); throw new StreamAccessException(message, cause); } private synchronized T mutate(OpStats stats, Mutation mutation) { if (writer == null) { throw new IllegalStateException("The log has encountered an error and cannot be used."); } long start = System.nanoTime(); if (!writer.isPresent()) { writer = Optional.of(writerFactory.get()); } try { return mutation.apply(writer.get()); } catch (TimeoutException e) { throw disableLog(stats.timeouts, "Timeout performing log " + stats.opName, e); } catch (Log.WriterFailedException e) { throw disableLog(stats.failures, "Problem performing log" + stats.opName, e); } finally { stats.timing.accumulate(System.nanoTime() - start); } } private LogPosition end() { return LogPosition.wrap(reader.ending()); } @VisibleForTesting static class LogPosition implements org.apache.aurora.scheduler.log.Log.Position { private final Log.Position underlying; LogPosition(Log.Position underlying) { this.underlying = underlying; } static LogPosition wrap(Log.Position position) { return new LogPosition(position); } Log.Position unwrap() { return underlying; } } private static class LogEntry implements org.apache.aurora.scheduler.log.Log.Entry { private final Log.Entry underlying; LogEntry(Log.Entry entry) { this.underlying = entry; } @Override public byte[] contents() { return underlying.data; } } }
blob data class, long method t t f data class, long method blob 0 10540 https://github.com/apache/aurora/blob/6ec953f27f7f80366d6bf4c8e7cba0e62a874753/src/main/java/org/apache/aurora/scheduler/log/mesos/MesosLog.java/#L145-L393 1 1264 10540
570   { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); }
blob blob, data class, long method t t t  data class, long method   0 5736 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 1 570 5736
4048   YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Primitive obsession 4. Data class 5. Message chains 6. Feature envy 7. Inappropriate intimacy (calling methods from parent class) 8. Mixed levels of abstraction 9. Code repetition (multiple use of "dis" variable) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } }
long method  Long method2 Long parameter list3 Primitive obsession4 Data class5 Message chains6 Feature envy7 Inappropriate intimacy (calling methods from parent class)8 Mixed levels of abstraction9 Code repetition (multiple use of "dis" variable) t f t     0 10697 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 2 4048 10697
1294    { "message": "YES I found bad smells the bad smells are:", "bad smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 10624 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 1 1294 10624
2202  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } }
blob data class t t f data class blob 0 13505 https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 1 2202 13505
1940   { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl
blob data class t t f data class blob 0 12484 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 1 1940 12484
297 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class DrillFilterItemStarReWriterRule { public static final ProjectOnScan PROJECT_ON_SCAN = new ProjectOnScan( RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.ProjectOnScan"); public static final FilterOnScan FILTER_ON_SCAN = new FilterOnScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillFilterItemStarReWriterRule.FilterOnScan"); public static final FilterProjectScan FILTER_PROJECT_SCAN = new FilterProjectScan( RelOptHelper.some(DrillFilterRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillFilterItemStarReWriterRule.FilterProjectScan"); private static class ProjectOnScan extends RelOptRule { ProjectOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillProjectRel projectRel = call.rel(0); DrillScanRel scanRel = call.rel(1); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(scanRel.getRowType().getFieldNames()); List projects = projectRel.getProjects(); for (RexNode project : projects) { project.accept(itemStarFieldsVisitor); } // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // re-write projects Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); List newProjects = new ArrayList<>(); for (RexNode node : projectRel.getChildExps()) { newProjects.add(node.accept(fieldsReWriter)); } DrillProjectRel newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, projectRel.getRowType()); if (ProjectRemoveRule.isTrivial(newProject)) { call.transformTo(newScan); } else { call.transformTo(newProject); } } } private static class FilterOnScan extends RelOptRule { FilterOnScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(1); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillScanRel scanRel = call.rel(1); transformFilterCall(filterRel, null, scanRel, call); } } private static class FilterProjectScan extends RelOptRule { FilterProjectScan(RelOptRuleOperand operand, String id) { super(operand, id); } @Override public boolean matches(RelOptRuleCall call) { DrillScanRel scan = call.rel(2); return scan.getGroupScan() instanceof AbstractParquetGroupScan && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { DrillFilterRel filterRel = call.rel(0); DrillProjectRel projectRel = call.rel(1); DrillScanRel scanRel = call.rel(2); transformFilterCall(filterRel, projectRel, scanRel, call); } } /** * Removes item star call from filter expression and propagates changes into project (if present) and scan. * * @param filterRel original filter expression * @param projectRel original project expression * @param scanRel original scan expression * @param call original rule call */ private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) { List fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames(); ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames); filterRel.getCondition().accept(itemStarFieldsVisitor); // if there are no item fields, no need to proceed further if (itemStarFieldsVisitor.hasNoItemStarFields()) { return; } Map itemStarFields = itemStarFieldsVisitor.getItemStarFields(); DrillScanRel newScan = createNewScan(scanRel, itemStarFields); // create new project if was present in call DrillProjectRel newProject = null; if (projectRel != null) { // add new projects to the already existing in original project int projectIndex = scanRel.getRowType().getFieldCount(); List newProjects = new ArrayList<>(projectRel.getProjects()); for (DesiredField desiredField : itemStarFields.values()) { newProjects.add(new RexInputRef(projectIndex, desiredField.getType())); projectIndex++; } RelDataType newProjectRowType = createNewRowType( projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet()); newProject = new DrillProjectRel( projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType); } // transform filter condition Map fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount()); FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper); RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter); // create new filter DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition); // wrap with project to have the same row type as before List newProjects = new ArrayList<>(); RelDataType rowType = filterRel.getRowType(); List fieldList = rowType.getFieldList(); for (RelDataTypeField field : fieldList) { RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType()); newProjects.add(inputRef); } DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType()); call.transformTo(wrapper); } /** * Creates new row type with merged original and new fields. * * @param typeFactory type factory * @param originalFields original fields * @param newFields new fields * @return new row type with original and new fields */ private static RelDataType createNewRowType(RelDataTypeFactory typeFactory, List originalFields, Collection newFields) { RelDataTypeHolder relDataTypeHolder = new RelDataTypeHolder(); // add original fields for (RelDataTypeField field : originalFields) { relDataTypeHolder.getField(typeFactory, field.getName()); } // add new fields for (String fieldName : newFields) { relDataTypeHolder.getField(typeFactory, fieldName); } return new RelDataTypeDrillImpl(relDataTypeHolder, typeFactory); } /** * Creates new scan with fields from original scan and fields used in item star operator. * * @param scanRel original scan expression * @param itemStarFields item star fields * @return new scan expression */ private static DrillScanRel createNewScan(DrillScanRel scanRel, Map itemStarFields) { RelDataType newScanRowType = createNewRowType( scanRel.getCluster().getTypeFactory(), scanRel.getRowType().getFieldList(), itemStarFields.keySet()); List columns = new ArrayList<>(scanRel.getColumns()); for (DesiredField desiredField : itemStarFields.values()) { String name = desiredField.getName(); PathSegment.NameSegment nameSegment = new PathSegment.NameSegment(name); columns.add(new SchemaPath(nameSegment)); } return new DrillScanRel( scanRel.getCluster(), scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL), scanRel.getTable(), newScanRowType, columns); } /** * Creates node mapper to replace item star calls with new input field references. * Starting index should be calculated from the last used input expression (i.e. scan expression). * NB: field reference index starts from 0 thus original field count can be taken as starting index * * @param desiredFields list of desired fields * @param startingIndex starting index * @return field mapper */ private static Map createFieldMapper(Collection desiredFields, int startingIndex) { Map fieldMapper = new HashMap<>(); int index = startingIndex; for (DesiredField desiredField : desiredFields) { for (RexNode node : desiredField.getNodes()) { // if field is referenced in more then one call, add each call to field mapper fieldMapper.put(node, index); } // increment index for the next node reference index++; } return fieldMapper; } /** * Traverses given node and stores all item star fields. * For the fields with the same name, stores original calls in a list, does not duplicate fields. * Holds state, should not be re-used. */ private static class ItemStarFieldsVisitor extends RexVisitorImpl { private final Map itemStarFields = new HashMap<>(); private final List fieldNames; ItemStarFieldsVisitor(List fieldNames) { super(true); this.fieldNames = fieldNames; } boolean hasNoItemStarFields() { return itemStarFields.isEmpty(); } Map getItemStarFields() { return itemStarFields; } @Override public RexNode visitCall(RexCall call) { // need to figure out field name and index String fieldName = FieldsReWriterUtil.getFieldNameFromItemStarField(call, fieldNames); if (fieldName != null) { // if there is call to the already existing field, store call, do not duplicate field DesiredField desiredField = itemStarFields.get(fieldName); if (desiredField == null) { itemStarFields.put(fieldName, new DesiredField(fieldName, call.getType(), call)); } else { desiredField.addNode(call); } } return super.visitCall(call); } } }
blob data class, long method t t f data class, long method blob 0 3123 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillFilterItemStarReWriterRule.java/#L52-L353 1 297 3123
4282  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } }
blob data class, long method t t f data class, long method blob 0 11274 https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 1 4282 11274
2544 {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } }
blob data class, long method t t f data class, long method blob 0 14788 https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 1 2544 14788
2630   YES, I found bad smells. The bad smells are: 1. Long method (AllocationManager) 2. Primitive obsession (AtomicLong, int) 3. Inappropriate intimacy (AllocationManager has direct access to BufferLedger) 4. Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator) 5. Inappropriate coupling (AllocationManager knows details about BufferLedger class) 6. Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes) 7. Data class (BufferLedger contains only getters and setters) 8. No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes) 9. Excessive commenting (explanation in comments is not always necessary) 10. No error handling for invalid inputs (e.g. in associate method) 11. Feature envy (BufferLedger has knowledge about AllocationManager's internals) 12. Magic numbers (values like 0 and 1 should be declared as constants) 13. Inappropriate visibility (BufferLedger has public inner class, should be private) 14. Inconsistent use of unit of time (nanoseconds and milliseconds are mixed) 15. Poor exception handling (some methods catch exceptions but do nothing with them) 16. Code duplication (similar code in associate method and transferBalance method) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class AllocationManager { private static final AtomicLong MANAGER_ID_GENERATOR = new AtomicLong(0); private static final AtomicLong LEDGER_ID_GENERATOR = new AtomicLong(0); static final PooledByteBufAllocatorL INNER_ALLOCATOR = new PooledByteBufAllocatorL(DrillMetrics.getRegistry()); private final RootAllocator root; private final long allocatorManagerId = MANAGER_ID_GENERATOR.incrementAndGet(); private final int size; private final UnsafeDirectLittleEndian underlying; private final IdentityHashMap map = new IdentityHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AutoCloseableLock readLock = new AutoCloseableLock(lock.readLock()); private final AutoCloseableLock writeLock = new AutoCloseableLock(lock.writeLock()); private final long amCreationTime = System.nanoTime(); private volatile BufferLedger owningLedger; private volatile long amDestructionTime = 0; AllocationManager(BaseAllocator accountingAllocator, int size) { Preconditions.checkNotNull(accountingAllocator); accountingAllocator.assertOpen(); this.root = accountingAllocator.root; this.underlying = INNER_ALLOCATOR.allocate(size); // we do a no retain association since our creator will want to retrieve the newly created ledger and will create a // reference count at that point this.owningLedger = associate(accountingAllocator, false); this.size = underlying.capacity(); } /** * Associate the existing underlying buffer with a new allocator. This will * increase the reference count to the provided ledger by 1. * * @param allocator * The target allocator to associate this buffer with. * @return The Ledger (new or existing) that associates the underlying buffer * to this new ledger. */ BufferLedger associate(final BaseAllocator allocator) { return associate(allocator, true); } private BufferLedger associate(final BaseAllocator allocator, final boolean retain) { allocator.assertOpen(); if (root != allocator.root) { throw new IllegalStateException( "A buffer can only be associated between two allocators that share the same root."); } try (@SuppressWarnings("unused") Closeable read = readLock.open()) { final BufferLedger ledger = map.get(allocator); if (ledger != null) { if (retain) { ledger.inc(); } return ledger; } } try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { // we have to recheck existing ledger since a second reader => writer could be competing with us. final BufferLedger existingLedger = map.get(allocator); if (existingLedger != null) { if (retain) { existingLedger.inc(); } return existingLedger; } final BufferLedger ledger = new BufferLedger(allocator, new ReleaseListener(allocator)); if (retain) { ledger.inc(); } BufferLedger oldLedger = map.put(allocator, ledger); Preconditions.checkArgument(oldLedger == null); allocator.associateLedger(ledger); return ledger; } } public static int chunkSize() { return INNER_ALLOCATOR.getChunkSize(); } /** * The way that a particular BufferLedger communicates back to the * AllocationManager that it now longer needs to hold a reference to * particular piece of memory. */ private class ReleaseListener { private final BufferAllocator allocator; public ReleaseListener(BufferAllocator allocator) { this.allocator = allocator; } /** * Can only be called when you already hold the writeLock. */ public void release() { allocator.assertOpen(); final BufferLedger oldLedger = map.remove(allocator); oldLedger.allocator.dissociateLedger(oldLedger); if (oldLedger == owningLedger) { if (map.isEmpty()) { // no one else owns, lets release. oldLedger.allocator.releaseBytes(size); underlying.release(); amDestructionTime = System.nanoTime(); owningLedger = null; } else { // we need to change the owning allocator. we've been removed so we'll get whatever is top of list BufferLedger newLedger = map.values().iterator().next(); // we'll forcefully transfer the ownership and not worry about whether we exceeded the limit // since this consumer can't do anything with this. oldLedger.transferBalance(newLedger); } } else { if (map.isEmpty()) { throw new IllegalStateException("The final removal of a ledger should be connected to the owning ledger."); } } } } /** * The reference manager that binds an allocator manager to a particular * BaseAllocator. Also responsible for creating a set of DrillBufs that share * a common fate and set of reference counts. As with AllocationManager, the * only reason this is public is due to DrillBuf being in io.netty.buffer * package. */ public class BufferLedger { private final IdentityHashMap buffers = BaseAllocator.DEBUG ? new IdentityHashMap() : null; private final long ledgerId = LEDGER_ID_GENERATOR.incrementAndGet(); // unique ID assigned to each ledger private final AtomicInteger bufRefCnt = new AtomicInteger(0); // start at zero so we can manage request for retain // correctly private final long lCreationTime = System.nanoTime(); private volatile long lDestructionTime = 0; private final BaseAllocator allocator; private final ReleaseListener listener; private final HistoricalLog historicalLog = BaseAllocator.DEBUG ? new HistoricalLog(BaseAllocator.DEBUG_LOG_LENGTH, "BufferLedger[%d]", 1) : null; private BufferLedger(BaseAllocator allocator, ReleaseListener listener) { this.allocator = allocator; this.listener = listener; } /** * Transfer any balance the current ledger has to the target ledger. In the case that the current ledger holds no * memory, no transfer is made to the new ledger. * @param target * The ledger to transfer ownership account to. * @return Whether transfer fit within target ledgers limits. */ public boolean transferBalance(final BufferLedger target) { Preconditions.checkNotNull(target); Preconditions.checkArgument(allocator.root == target.allocator.root, "You can only transfer between two allocators that share the same root."); allocator.assertOpen(); target.allocator.assertOpen(); // if we're transferring to ourself, just return. if (target == this) { return true; } // since two balance transfers out from the allocator manager could cause incorrect accounting, we need to ensure // that this won't happen by synchronizing on the allocator manager instance. try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { if (owningLedger != this) { return true; } if (BaseAllocator.DEBUG) { this.historicalLog.recordEvent("transferBalance(%s)", target.allocator.name); target.historicalLog.recordEvent("incoming(from %s)", owningLedger.allocator.name); } boolean overlimit = target.allocator.forceAllocate(size); allocator.releaseBytes(size); owningLedger = target; return overlimit; } } /** * Print the current ledger state to a the provided StringBuilder. * @param sb * The StringBuilder to populate. * @param indent * The level of indentation to position the data. * @param verbosity * The level of verbosity to print. */ public void print(StringBuilder sb, int indent, Verbosity verbosity) { indent(sb, indent) .append("ledger[") .append(ledgerId) .append("] allocator: ") .append(allocator.name) .append("), isOwning: ") .append(owningLedger == this) .append(", size: ") .append(size) .append(", references: ") .append(bufRefCnt.get()) .append(", life: ") .append(lCreationTime) .append("..") .append(lDestructionTime) .append(", allocatorManager: [") .append(AllocationManager.this.allocatorManagerId) .append(", life: ") .append(amCreationTime) .append("..") .append(amDestructionTime); if (!BaseAllocator.DEBUG) { sb.append("]\n"); } else { synchronized (buffers) { sb.append("] holds ") .append(buffers.size()) .append(" buffers. \n"); for (DrillBuf buf : buffers.keySet()) { buf.print(sb, indent + 2, verbosity); sb.append('\n'); } } } } private void inc() { bufRefCnt.incrementAndGet(); } /** * Decrement the ledger's reference count. If the ledger is decremented to * zero, this ledger should release its ownership back to the * AllocationManager */ public int decrement(int decrement) { allocator.assertOpen(); final int outcome; try (@SuppressWarnings("unused") Closeable write = writeLock.open()) { outcome = bufRefCnt.addAndGet(-decrement); if (outcome == 0) { lDestructionTime = System.nanoTime(); listener.release(); } } return outcome; } /** * Returns the ledger associated with a particular BufferAllocator. If the * BufferAllocator doesn't currently have a ledger associated with this * AllocationManager, a new one is created. This is placed on BufferLedger * rather than AllocationManager directly because DrillBufs don't have * access to AllocationManager and they are the ones responsible for * exposing the ability to associate multiple allocators with a particular * piece of underlying memory. Note that this will increment the reference * count of this ledger by one to ensure the ledger isn't destroyed before * use. * * @param allocator * @return The ledger associated with a particular BufferAllocator. */ public BufferLedger getLedgerForAllocator(BufferAllocator allocator) { return associate((BaseAllocator) allocator); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * Does not impact reference count. Typically used for slicing. * * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @return A new DrillBuf that shares references with all DrillBufs * associated with this BufferLedger */ public DrillBuf newDrillBuf(int offset, int length) { allocator.assertOpen(); return newDrillBuf(offset, length, null); } /** * Create a new DrillBuf associated with this AllocationManager and memory. * @param offset * The offset in bytes to start this new DrillBuf. * @param length * The length in bytes that this DrillBuf will provide access to. * @param manager * An optional BufferManager argument that can be used to manage expansion of this DrillBuf. * @return A new DrillBuf that shares references with all DrillBufs associated with this BufferLedger. */ public DrillBuf newDrillBuf(int offset, int length, BufferManager manager) { allocator.assertOpen(); final DrillBuf buf = new DrillBuf( bufRefCnt, this, underlying, manager, allocator.getAsByteBufAllocator(), offset, length, false); if (BaseAllocator.DEBUG) { historicalLog.recordEvent( "DrillBuf(BufferLedger, BufferAllocator[%s], UnsafeDirectLittleEndian[identityHashCode == " + "%d](%s)) => ledger hc == %d", allocator.name, System.identityHashCode(buf), buf.toString(), System.identityHashCode(this)); synchronized (buffers) { buffers.put(buf, null); } } return buf; } /** * The total size (in bytes) of memory underlying this ledger. * * @return Size in bytes */ public int getSize() { return size; } /** * Amount of memory accounted for by this ledger. This is either getSize() if this is the owning ledger for the * memory or zero in the case that this is not the owning ledger associated with this memory. * * @return Amount of accounted(owned) memory associated with this ledger. */ public int getAccountedSize() { try (@SuppressWarnings("unused") Closeable read = readLock.open()) { if (owningLedger == this) { return size; } else { return 0; } } } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected UnsafeDirectLittleEndian getUnderlying() { return underlying; } /** * Package visible for debugging/verification only. */ @VisibleForTesting protected boolean isOwningLedger() { return this == owningLedger; } } }
blob  Long method (AllocationManager)2 Primitive obsession (AtomicLong, int)3 Inappropriate intimacy (AllocationManager has direct access to BufferLedger)4 Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator)5 Inappropriate coupling (AllocationManager knows details about BufferLedger class)6 Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes)7 Data class (BufferLedger contains only getters and setters)8 No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes)9 Excessive commenting (explanation in comments is not always necessary) t f f . Long method (AllocationManager)2. Primitive obsession (AtomicLong, int)3. Inappropriate intimacy (AllocationManager has direct access to BufferLedger)4. Inconsistent naming (getLedgerForAllocator should be getLedgerForBufferAllocator)5. Inappropriate coupling (AllocationManager knows details about BufferLedger class)6. Lock coupling (AllocationManager and BufferLedger both use lock, but for different purposes)7. Data class (BufferLedger contains only getters and setters)8. No encapsulation of fields in BufferLedger class (fields are public and directly accessed by other classes)9. Excessive commenting (explanation in comments is not always necessary) blob 0 15098 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/memory/base/src/main/java/org/apache/drill/exec/memory/AllocationManager.java/#L60-L451 2 2630 15098
610  { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } }
blob data class, long method t t f data class, long method blob 0 6126 https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 1 610 6126
1865      { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } }
blob data class, long method t t f data class, long method blob 0 12235 https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 1 1865 12235
758    { "message": "YES I found bad smells", "bad_smells_are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } }
blob data class t t f data class blob 0 7065 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 1 758 7065
4676    { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } }
long method long method, data class t t t  data class   0 12504 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 1 4676 12504
370  { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static Class getPropertyEditorClass(final Object bean, final String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); }
feature envy long method, data class t t f long method, data class feature envy 0 3845 https://github.com/apache/commons-beanutils/blob/33a067788f2a414c0b019f8d8974cc455c1982a4/src/main/java/org/apache/commons/beanutils2/PropertyUtils.java/#L458-L464 1 370 3845
18 {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class LiveSignalEnforcement extends AbstractEnforcement { private static final int CACHE_TIMEOUT_SECONDS = 2 * 60; private final EnforcerRetriever enforcerRetriever; private final Cache responseReceivers; private LiveSignalEnforcement(final Context context, final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { super(context); requireNonNull(thingIdCache); requireNonNull(policyEnforcerCache); requireNonNull(aclEnforcerCache); enforcerRetriever = PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache); final Caffeine caffeine = Caffeine.newBuilder() .expireAfterWrite(CACHE_TIMEOUT_SECONDS, TimeUnit.SECONDS); responseReceivers = CaffeineCache.of(caffeine); } /** * {@link EnforcementProvider} for {@link LiveSignalEnforcement}. */ public static final class Provider implements EnforcementProvider { private final Cache> thingIdCache; private final Cache> policyEnforcerCache; private final Cache> aclEnforcerCache; /** * Constructor. * * @param thingIdCache the thing-id-cache. * @param policyEnforcerCache the policy-enforcer cache. * @param aclEnforcerCache the acl-enforcer cache. */ public Provider(final Cache> thingIdCache, final Cache> policyEnforcerCache, final Cache> aclEnforcerCache) { this.thingIdCache = requireNonNull(thingIdCache); this.policyEnforcerCache = requireNonNull(policyEnforcerCache); this.aclEnforcerCache = requireNonNull(aclEnforcerCache); } @Override public Class getCommandClass() { return Signal.class; } @Override public boolean isApplicable(final Signal signal) { return LiveSignalEnforcement.isLiveSignal(signal); } @Override public AbstractEnforcement createEnforcement(final Context context) { return new LiveSignalEnforcement(context, thingIdCache, policyEnforcerCache, aclEnforcerCache); } } @Override public CompletionStage enforce(final Signal signal, final ActorRef sender, final DiagnosticLoggingAdapter log) { LogUtil.enhanceLogWithCorrelationIdOrRandom(signal); return enforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> { if (enforcerEntry.exists()) { final Enforcer enforcer = enforcerEntry.getValue(); final String correlationId = signal.getDittoHeaders().getCorrelationId().get(); if (signal instanceof SendClaimMessage) { // claim messages require no enforcement, publish them right away: publishMessageCommand((SendClaimMessage) signal, enforcer, sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof CommandResponse) { // no enforcement for responses required - the original sender will get the answer: final Optional responseReceiver = responseReceivers.getBlocking(correlationId); if (responseReceiver.isPresent()) { responseReceiver.get().tell(signal, sender); responseReceivers.invalidate(correlationId); } else { log(signal).warning("No outstanding responses receiver for CommandResponse <{}>", signal.getType()); } } else if (signal instanceof Command) { // enforce both Live Commands and MessageCommands if (signal instanceof MessageCommand) { final boolean wasPublished = enforceMessageCommand((MessageCommand) signal, enforcer, sender); if (wasPublished && signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else if (signal instanceof ThingCommand) { // enforce Live Thing Commands final boolean authorized; if (enforcer instanceof AclEnforcer) { authorized = ThingCommandEnforcement.authorizeByAcl(enforcer, (ThingCommand) signal) .isPresent(); } else { authorized = ThingCommandEnforcement.authorizeByPolicy(enforcer, (ThingCommand) signal) .isPresent(); } if (authorized) { final Command withReadSubjects = addReadSubjectsToThingSignal((Command) signal, enforcer); log(withReadSubjects).info("Live Command was authorized: <{}>", withReadSubjects); publishToMediator(withReadSubjects, StreamingType.LIVE_COMMANDS.getDistributedPubSubTopic(), sender); if (signal.getDittoHeaders().isResponseRequired()) { responseReceivers.put(correlationId, sender); } } else { log(signal).info("Live Command was NOT authorized: <{}>", signal); ThingCommandEnforcement.respondWithError((ThingCommand) signal, sender, self()); } } else { log(signal).error("Ignoring unsupported live signal: <{}>", signal); } } else if (signal instanceof ThingEvent) { // enforce Live Events final boolean authorized = enforcer.hasUnrestrictedPermissions( // only check access to root resource for now PoliciesResourceType.thingResource("/"), signal.getDittoHeaders().getAuthorizationContext(), WRITE); if (authorized) { log(signal).info("Live Event was authorized: <{}>", signal); final Event withReadSubjects = addReadSubjectsToThingSignal((Event) signal, enforcer); publishToMediator(withReadSubjects, StreamingType.LIVE_EVENTS.getDistributedPubSubTopic(), sender); } else { final EventSendNotAllowedException eventSendNotAllowedException = EventSendNotAllowedException.newBuilder(((ThingEvent) signal).getThingId()) .dittoHeaders(signal.getDittoHeaders()) .build(); log(signal).info("Live Event was NOT authorized: <{}>", signal); replyToSender(eventSendNotAllowedException, sender); } } } else { // drop live command to nonexistent things and respond with error. log(signal).info("Command of type <{}> with ID <{}> could not be dispatched as no enforcer could be" + " looked up! Answering with ThingNotAccessibleException.", signal.getType(), signal.getId()); final ThingNotAccessibleException error = ThingNotAccessibleException.newBuilder(entityId().getId()) .dittoHeaders(signal.getDittoHeaders()) .build(); replyToSender(error, sender); } }); } /** * Tests whether a signal is applicable for live signal enforcement. * * @param signal the signal to test. * @return whether the signal belongs to the live channel. */ static boolean isLiveSignal(final Signal signal) { return signal.getDittoHeaders().getChannel().filter(TopicPath.Channel.LIVE.getName()::equals).isPresent(); } private boolean enforceMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { if (isAuthorized(command, enforcer)) { publishMessageCommand(command, enforcer, sender); return true; } else { rejectMessageCommand(command, sender); return false; } } private void publishMessageCommand(final MessageCommand command, final Enforcer enforcer, final ActorRef sender) { final ResourceKey resourceKey = ResourceKey.newInstance(MessageCommand.RESOURCE_TYPE, command.getResourcePath()); final Set messageReaders = enforcer.getSubjectIdsWithPermission(resourceKey, Permission.READ) .getGranted(); final DittoHeaders headersWithReadSubjects = command.getDittoHeaders() .toBuilder() .readSubjects(messageReaders) .build(); final MessageCommand commandWithReadSubjects = command.setDittoHeaders(headersWithReadSubjects); publishToMediator(commandWithReadSubjects, commandWithReadSubjects.getTypePrefix(), sender); // answer the sender immediately for fire-and-forget message commands. getResponseForFireAndForgetMessage(commandWithReadSubjects) .ifPresent(response -> replyToSender(response, sender)); } private void rejectMessageCommand(final MessageCommand command, final ActorRef sender) { final MessageSendNotAllowedException error = MessageSendNotAllowedException.newBuilder(command.getThingId()) .dittoHeaders(command.getDittoHeaders()) .build(); log(command).info( "The command <{}> was not forwarded due to insufficient rights {}: {} - AuthorizationSubjects: {}", command.getType(), error.getClass().getSimpleName(), error.getMessage(), command.getDittoHeaders().getAuthorizationSubjects()); replyToSender(error, sender); } private void publishToMediator(final Signal command, final String pubSubTopic, final ActorRef sender) { // using pub/sub to publish the command to any interested parties (e.g. a Websocket): log(command).debug("Publish message to pub-sub: <{}>", pubSubTopic); final DistributedPubSubMediator.Publish publishMessage = new DistributedPubSubMediator.Publish(pubSubTopic, command, true); pubSubMediator().tell(publishMessage, sender); } private static boolean isAuthorized(final MessageCommand command, final Enforcer enforcer) { return enforcer.hasUnrestrictedPermissions( PoliciesResourceType.messageResource(command.getResourcePath()), command.getDittoHeaders().getAuthorizationContext(), WRITE); } /** * Creates an @{SendMessageAcceptedResponse} for a message command if it is fire-and-forget. * * @param command The message command. * @return The HTTP response if the message command is fire-and-forget, {@code Optional.empty()} otherwise. */ private static Optional getResponseForFireAndForgetMessage( final MessageCommand command) { if (isFireAndForgetMessage(command)) { return Optional.of( SendMessageAcceptedResponse.newInstance(command.getThingId(), command.getMessage().getHeaders(), command.getDittoHeaders())); } else { return Optional.empty(); } } /** * Tests whether a message command is fire-and-forget. * * @param command The message command. * @return {@code true} if the message's timeout header is 0 or if the message is flagged not to require a response, * {@code false} otherwise. */ private static boolean isFireAndForgetMessage(final MessageCommand command) { return command.getMessage() .getTimeout() .map(Duration::isZero) .orElseGet(() -> !command.getDittoHeaders().isResponseRequired()); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 660 https://github.com/eclipse/ditto/blob/7fec826b94f3711f6c6ef6be1685b60bd1a8ccb5/services/concierge/enforcement/src/main/java/org/eclipse/ditto/services/concierge/enforcement/LiveSignalEnforcement.java/#L57-L319 1 18 660
903 {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; }
long method long method, data class t t t  data class   0 8170 https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 1 903 8170
824    { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ArrayMap extends AbstractMap { private Object[] table; private int size; protected transient Collection values; public ArrayMap() { this(32); } public ArrayMap(int capacity) { table = new Object[capacity * 2]; size = 0; } @Override @SuppressWarnings("unchecked") public V get(Object key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } return null; } @Override @SuppressWarnings("unchecked") public V put(K key, V value) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { V old = (V) table[i + 1]; table[i + 1] = value; return old; } } if (size * 2 == table.length) { Object[] n = new Object[table.length * 2]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = value; return null; } @SuppressWarnings("unchecked") public V getOrCompute(K key) { for (int i = 0, l = size << 1; i < l; i += 2) { if (key.equals(table[i])) { return (V) table[i + 1]; } } V v = compute(key); if (size << 1 == table.length) { Object[] n = new Object[table.length << 1]; System.arraycopy(table, 0, n, 0, table.length); table = n; } int i = size++ << 1; table[i++] = key; table[i] = v; return v; } protected V compute(K key) { throw new UnsupportedOperationException(); } @Override public Collection values() { if (values == null) { values = new AbstractCollection() { @Override public Iterator iterator() { return new Iterator() { int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public V next() { if (index >= size) { throw new NoSuchElementException(); } return (V) table[(index++ << 1) + 1]; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } return values; } @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { FastEntry entry = new FastEntry(); int index = 0; public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") public FastEntry next() { if (index >= size) { throw new NoSuchElementException(); } int i = index << 1; entry.key = (K) table[i]; entry.value = (V) table[i + 1]; index++; return entry; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return size; } }; } static class FastEntry implements Entry { K key; V value; public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } } }
blob long method, data class t t f long method, data class blob 0 7711 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/resolver/src/main/java/org/apache/felix/resolver/util/ArrayMap.java/#L23-L184 1 824 7711
5107 { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Complex code structure", "Data class", "Duplicated code", "Feature envy" ] } I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class XMLDOMWriterImpl implements XMLStreamWriterBase { private Document ownerDoc = null; private Node currentNode = null; private Node node = null; private NamespaceSupport namespaceContext = null; private boolean [] needContextPop = null; private StringBuffer stringBuffer = null; private int resizeValue = 20; private int depth = 0; /** * Creates a new instance of XMLDOMwriterImpl * @param result DOMResult object @javax.xml.transform.dom.DOMResult */ public XMLDOMWriterImpl(DOMResult result) { node = result.getNode(); if( node.getNodeType() == Node.DOCUMENT_NODE){ ownerDoc = (Document)node; currentNode = ownerDoc; }else{ ownerDoc = node.getOwnerDocument(); currentNode = node; } stringBuffer = new StringBuffer(); needContextPop = new boolean[resizeValue]; namespaceContext = new NamespaceSupport(); } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void close() throws XMLStreamException { //no-op } /** * This method has no effect when called. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void flush() throws XMLStreamException { //no-op } /** * {@inheritDoc} * @return {@inheritDoc} */ public javax.xml.namespace.NamespaceContext getNamespaceContext() { return null; } /** * {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} * @return {@inheritDoc} */ public String getPrefix(String namespaceURI) throws XMLStreamException { String prefix = null; if(this.namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } return prefix; } /** * Is not supported in this implementation. * @param str {@inheritDoc} * @throws java.lang.IllegalArgumentException {@inheritDoc} * @return {@inheritDoc} */ public Object getProperty(String str) throws IllegalArgumentException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setDefaultNamespace(String uri) throws XMLStreamException { namespaceContext.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * {@inheritDoc} * @param namespaceContext {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setNamespaceContext(javax.xml.namespace.NamespaceContext namespaceContext) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Is not supported in this version of the implementation. * @param prefix {@inheritDoc} * @param uri {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void setPrefix(String prefix, String uri) throws XMLStreamException { if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } namespaceContext.declarePrefix(prefix, uri); if(!needContextPop[depth]){ needContextPop[depth] = true; } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String localName, String value) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ Attr attr = ownerDoc.createAttribute(localName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNode(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @param value {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("prefix cannot be null"); } String qualifiedName = null; if(prefix.isEmpty()){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName); attr.setValue(value); ((Element)currentNode).setAttributeNodeNS(attr); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * Creates a CDATA object @see org.w3c.dom.CDATASection. * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCData(String data) throws XMLStreamException { if(data == null){ throw new XMLStreamException("CDATA cannot be null"); } CDATASection cdata = ownerDoc.createCDATASection(data); getNode().appendChild(cdata); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param charData {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(String charData) throws XMLStreamException { Text text = ownerDoc.createTextNode(charData); currentNode.appendChild(text); } /** * Creates a character object @see org.w3c.dom.Text and appends it to the current * element in the DOM tree. * @param values {@inheritDoc} * @param param {@inheritDoc} * @param param2 {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeCharacters(char[] values, int param, int param2) throws XMLStreamException { Text text = ownerDoc.createTextNode(new String(values,param,param2)); currentNode.appendChild(text); } /** * Creates a Comment object @see org.w3c.dom.Comment and appends it to the current * element in the DOM tree. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeComment(String str) throws XMLStreamException { Comment comment = ownerDoc.createComment(str); getNode().appendChild(comment); } /** * This method is not supported in this implementation. * @param str {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDTD(String str) throws XMLStreamException { throw new UnsupportedOperationException(); } /** * Creates a DOM attribute and adds it to the current element in the DOM tree. * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(currentNode.getNodeType() == Node.ELEMENT_NODE){ String qname = XMLConstants.XMLNS_ATTRIBUTE; ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); }else{ //Convert node type to String throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() + "and does not allow attributes to be set "); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } } } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } //currentNode = element; } } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } String qualifiedName = null; if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qualifiedName); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } } } /** * Will reset current Node pointer maintained by the implementation. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndDocument() throws XMLStreamException { //What do you want me to do eh! :) currentNode = null; for(int i=0; i< depth;i++){ if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } depth =0; } /** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; } /** * Is not supported in this implementation. * @param name {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEntityRef(String name) throws XMLStreamException { EntityReference er = ownerDoc.createEntityReference(name); currentNode.appendChild(er); } /** * creates a namespace attribute and will associate it with the current element in * the DOM tree. * @param prefix {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new XMLStreamException("prefix cannot be null"); } if (namespaceURI == null) { throw new XMLStreamException("NamespaceURI cannot be null"); } String qname = null; if (prefix.isEmpty()) { qname = XMLConstants.XMLNS_ATTRIBUTE; } else { qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix); } ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI); } /** * is not supported in this release. * @param target {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, ""); currentNode.appendChild(pi); } /** * is not supported in this release. * @param target {@inheritDoc} * @param data {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeProcessingInstruction(String target, String data) throws XMLStreamException { if(target == null){ throw new XMLStreamException("Target cannot be null"); } ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, data); currentNode.appendChild(pi); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument() throws XMLStreamException { ownerDoc.setXmlVersion("1.0"); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(null, version, false, false); } /** * will set version on the Document object when the DOM Node passed to this implementation * supports DOM Level3 API's. * @param encoding {@inheritDoc} * @param version {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartDocument(String encoding, String version) throws XMLStreamException { writeStartDocument(encoding, version, false, false); } @Override public void writeStartDocument(String encoding, String version, boolean standalone, boolean standaloneSet) throws XMLStreamException { if (encoding != null && ownerDoc.getClass().isAssignableFrom(DocumentImpl.class)) { ((DocumentImpl)ownerDoc).setXmlEncoding(encoding); } ownerDoc.setXmlVersion(version); if (standaloneSet) { ownerDoc.setXmlStandalone(standalone); } } /** * creates a DOM Element and appends it to the current element in the tree. * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String localName) throws XMLStreamException { if(ownerDoc != null){ Element element = ownerDoc.createElement(localName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param namespaceURI {@inheritDoc} * @param localName {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { if(ownerDoc != null){ String qualifiedName = null; String prefix = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(namespaceContext != null){ prefix = namespaceContext.getPrefix(namespaceURI); } if(prefix == null){ throw new XMLStreamException("Namespace URI "+namespaceURI + "is not bound to any prefix" ); } if("".equals(prefix)){ qualifiedName = localName; }else{ qualifiedName = getQName(prefix,localName); } Element element = ownerDoc.createElementNS(namespaceURI, qualifiedName); if(currentNode!=null){ currentNode.appendChild(element); }else{ ownerDoc.appendChild(element); } currentNode = element; } if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } /** * creates a DOM Element and appends it to the current element in the tree. * @param prefix {@inheritDoc} * @param localName {@inheritDoc} * @param namespaceURI {@inheritDoc} * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if(ownerDoc != null){ String qname = null; if(namespaceURI == null ){ throw new XMLStreamException("NamespaceURI cannot be null"); } if(localName == null){ throw new XMLStreamException("Local name cannot be null"); } if(prefix == null){ throw new XMLStreamException("Prefix cannot be null"); } if(prefix.isEmpty()){ qname = localName; }else{ qname = getQName(prefix,localName); } Element el = ownerDoc.createElementNS(namespaceURI,qname); if(currentNode!=null){ currentNode.appendChild(el); }else{ ownerDoc.appendChild(el); } currentNode = el; if(needContextPop[depth]){ namespaceContext.pushContext(); } incDepth(); } } private String getQName(String prefix , String localName){ stringBuffer.setLength(0); stringBuffer.append(prefix); stringBuffer.append(":"); stringBuffer.append(localName); return stringBuffer.toString(); } private Node getNode(){ if(currentNode == null){ return ownerDoc; } else{ return currentNode; } } private void incDepth() { depth++; if (depth == needContextPop.length) { boolean[] array = new boolean[depth + resizeValue]; System.arraycopy(needContextPop, 0, array, 0, depth); needContextPop = array; } } }
blob long method, complex code structure, data class, duplicated code, feature envy t t f long method, complex code structure, data class, duplicated code, feature envy blob 0 14309 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/xml/internal/stream/writers/XMLDOMWriterImpl.java/#L62-L717 2 5107 14309
2462 {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TezClientUtils { private static Log LOG = LogFactory.getLog(TezClientUtils.class); private static final int UTF8_CHUNK_SIZE = 16 * 1024; /** * Setup LocalResource map for Tez jars based on provided Configuration * * @param conf * Configuration to use to access Tez jars' locations * @param credentials * a credentials instance into which tokens for the Tez local * resources will be populated * @return Map of LocalResources to use when launching Tez AM * @throws IOException */ static Map setupTezJarsLocalResources( TezConfiguration conf, Credentials credentials) throws IOException { Preconditions.checkNotNull(credentials, "A non-null credentials object should be specified"); Map tezJarResources = new HashMap(); if (conf.getBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false)){ LOG.info("Ignoring '" + TezConfiguration.TEZ_LIB_URIS + "' since '" + TezConfiguration.TEZ_IGNORE_LIB_URIS + "' is set to true"); } else { // Add tez jars to local resource String[] tezJarUris = conf.getStrings(TezConfiguration.TEZ_LIB_URIS); if (tezJarUris == null || tezJarUris.length == 0) { throw new TezUncheckedException("Invalid configuration of tez jars" + ", " + TezConfiguration.TEZ_LIB_URIS + " is not defined in the configurartion"); } List tezJarPaths = Lists.newArrayListWithCapacity(tezJarUris.length); for (String tezJarUri : tezJarUris) { URI uri; try { uri = new URI(tezJarUri.trim()); } catch (URISyntaxException e) { String message = "Invalid URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message, e); } if (!uri.isAbsolute()) { String message = "Non-absolute URI defined in configuration for" + " location of TEZ jars. providedURI=" + tezJarUri; LOG.error(message); throw new TezUncheckedException(message); } Path p = new Path(uri); FileSystem pathfs = p.getFileSystem(conf); p = pathfs.makeQualified(p); tezJarPaths.add(p); RemoteIterator iter = pathfs.listFiles(p, false); while (iter.hasNext()) { LocatedFileStatus fStatus = iter.next(); String rsrcName = fStatus.getPath().getName(); // FIXME currently not checking for duplicates due to quirks // in assembly generation if (tezJarResources.containsKey(rsrcName)) { String message = "Duplicate resource found" + ", resourceName=" + rsrcName + ", existingPath=" + tezJarResources.get(rsrcName).getResource().toString() + ", newPath=" + fStatus.getPath(); LOG.warn(message); // throw new TezUncheckedException(message); } tezJarResources.put(rsrcName, LocalResource.newInstance( ConverterUtils.getYarnUrlFromPath(fStatus.getPath()), LocalResourceType.FILE, LocalResourceVisibility.PUBLIC, fStatus.getLen(), fStatus.getModificationTime())); } } if (tezJarResources.isEmpty()) { throw new TezUncheckedException( "No files found in locations specified in " + TezConfiguration.TEZ_LIB_URIS + " . Locations: " + StringUtils.join(tezJarUris, ',')); } else { // Obtain credentials. TokenCache.obtainTokensForFileSystems(credentials, tezJarPaths.toArray(new Path[tezJarPaths.size()]), conf); } } return tezJarResources; } static void processTezLocalCredentialsFile(Credentials credentials, Configuration conf) throws IOException { String path = conf.get(TezJobConfig.TEZ_CREDENTIALS_PATH); if (path == null) { return; } else { TokenCache.mergeBinaryTokens(credentials, conf, path); } } /** * Verify or create the Staging area directory on the configured Filesystem * @param stagingArea Staging area directory path * @return the FileSytem for the staging area directory * @throws IOException */ public static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea) throws IOException { FileSystem fs = stagingArea.getFileSystem(conf); String realUser; String currentUser; UserGroupInformation ugi = UserGroupInformation.getLoginUser(); realUser = ugi.getShortUserName(); currentUser = UserGroupInformation.getCurrentUser().getShortUserName(); if (fs.exists(stagingArea)) { FileStatus fsStatus = fs.getFileStatus(stagingArea); String owner = fsStatus.getOwner(); if (!(owner.equals(currentUser) || owner.equals(realUser))) { throw new IOException("The ownership on the staging directory " + stagingArea + " is not as expected. " + "It is owned by " + owner + ". The directory must " + "be owned by the submitter " + currentUser + " or " + "by " + realUser); } if (!fsStatus.getPermission().equals(TezCommonUtils.TEZ_AM_DIR_PERMISSION)) { LOG.info("Permissions on staging directory " + stagingArea + " are " + "incorrect: " + fsStatus.getPermission() + ". Fixing permissions " + "to correct value " + TezCommonUtils.TEZ_AM_DIR_PERMISSION); fs.setPermission(stagingArea, TezCommonUtils.TEZ_AM_DIR_PERMISSION); } } else { TezCommonUtils.mkDirForAM(fs, stagingArea); } return fs; } /** * Obtains tokens for the DAG based on the list of URIs setup in the DAG. The * fetched credentials are populated back into the DAG and can be retrieved * via dag.getCredentials * * @param dag * the dag for which credentials need to be setup * @param sessionCredentials * session credentials which have already been obtained, and will be * required for the DAG * @param conf * @throws IOException */ @Private static void setupDAGCredentials(DAG dag, Credentials sessionCredentials, Configuration conf) throws IOException { Preconditions.checkNotNull(sessionCredentials); LogUtils.logCredentials(LOG, sessionCredentials, "session"); Credentials dagCredentials = dag.getCredentials(); if (dagCredentials == null) { dagCredentials = new Credentials(); dag.setCredentials(dagCredentials); } // All session creds are required for the DAG. dagCredentials.mergeAll(sessionCredentials); // Add additional credentials based on any URIs that the user may have specified. // Obtain Credentials for any paths that the user may have configured. Collection uris = dag.getURIsForCredentials(); if (uris != null && !uris.isEmpty()) { Iterator pathIter = Iterators.transform(uris.iterator(), new Function() { @Override public Path apply(URI input) { return new Path(input); } }); Path[] paths = Iterators.toArray(pathIter, Path.class); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } // Obtain Credentials for the local resources configured on the DAG try { Set lrPaths = new HashSet(); for (Vertex v: dag.getVertices()) { for (LocalResource lr: v.getTaskLocalFiles().values()) { lrPaths.add(ConverterUtils.getPathFromYarnURL(lr.getResource())); } } Path[] paths = lrPaths.toArray(new Path[lrPaths.size()]); TokenCache.obtainTokensForFileSystems(dagCredentials, paths, conf); } catch (URISyntaxException e) { throw new IOException(e); } } /** * Create an ApplicationSubmissionContext to launch a Tez AM * @param conf TezConfiguration * @param appId Application Id * @param dag DAG to be submitted * @param amName Name for the application * @param amConfig AM Configuration * @param tezJarResources Resources to be used by the AM * @param sessionCreds the credential object which will be populated with session specific * @return an ApplicationSubmissionContext to launch a Tez AM * @throws IOException * @throws YarnException */ static ApplicationSubmissionContext createApplicationSubmissionContext( TezConfiguration conf, ApplicationId appId, DAG dag, String amName, AMConfiguration amConfig, Map tezJarResources, Credentials sessionCreds) throws IOException, YarnException{ Preconditions.checkNotNull(sessionCreds); FileSystem fs = TezClientUtils.ensureStagingDirExists(conf, TezCommonUtils.getTezBaseStagingPath(conf)); String strAppId = appId.toString(); Path tezSysStagingPath = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Path binaryConfPath = TezCommonUtils.getTezConfStagingPath(tezSysStagingPath); binaryConfPath = fs.makeQualified(binaryConfPath); // Setup resource requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB, TezConfiguration.TEZ_AM_RESOURCE_MEMORY_MB_DEFAULT)); capability.setVirtualCores( amConfig.getTezConfiguration().getInt(TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES, TezConfiguration.TEZ_AM_RESOURCE_CPU_VCORES_DEFAULT)); if (LOG.isDebugEnabled()) { LOG.debug("AppMaster capability = " + capability); } // Setup required Credentials for the AM launch. DAG specific credentials // are handled separately. ByteBuffer securityTokens = null; // Setup security tokens Credentials amLaunchCredentials = new Credentials(); if (amConfig.getCredentials() != null) { amLaunchCredentials.addAll(amConfig.getCredentials()); } // Add Staging dir creds to the list of session credentials. TokenCache.obtainTokensForFileSystems(sessionCreds, new Path[] {binaryConfPath}, conf); // Add session specific credentials to the AM credentials. amLaunchCredentials.mergeAll(sessionCreds); DataOutputBuffer dob = new DataOutputBuffer(); amLaunchCredentials.writeTokenStorageToStream(dob); securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // Need to set credentials based on DAG and the URIs which have been set for the DAG. if (dag != null) { setupDAGCredentials(dag, sessionCreds, conf); } // Setup the command to run the AM List vargs = new ArrayList(8); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); String amOpts = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_AM_LAUNCH_CMD_OPTS_DEFAULT); amOpts = maybeAddDefaultMemoryJavaOpts(amOpts, capability, amConfig.getTezConfiguration().getDouble(TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION, TezConfiguration.TEZ_CONTAINER_MAX_JAVA_HEAP_FRACTION_DEFAULT)); vargs.add(amOpts); String amLogLevel = amConfig.getTezConfiguration().get( TezConfiguration.TEZ_AM_LOG_LEVEL, TezConfiguration.TEZ_AM_LOG_LEVEL_DEFAULT); maybeAddDefaultLoggingJavaOpts(amLogLevel, vargs); // FIX sun bug mentioned in TEZ-327 vargs.add("-Dsun.nio.ch.bugLevel=''"); vargs.add(TezConfiguration.TEZ_APPLICATION_MASTER_CLASS); if (dag == null) { vargs.add("--" + TezConstants.TEZ_SESSION_MODE_CLI_OPTION); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDOUT); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + File.separator + ApplicationConstants.STDERR); Vector vargsFinal = new Vector(8); // Final command StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } vargsFinal.add(mergedCommand.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Command to launch container for ApplicationMaster is : " + mergedCommand); } Map environment = new TreeMap(); TezYARNUtils.setupDefaultEnv(environment, conf, TezConfiguration.TEZ_AM_LAUNCH_ENV, TezConfiguration.TEZ_AM_LAUNCH_ENV_DEFAULT); // finally apply env set in the code. This could potentially be removed in // TEZ-692 if (amConfig.getEnv() != null) { for (Map.Entry entry : amConfig.getEnv().entrySet()) { TezYARNUtils.addToEnvironment(environment, entry.getKey(), entry.getValue(), File.pathSeparator); } } Map localResources = new TreeMap(); // Not fetching credentials for AMLocalResources. Expect this to be provided via AMCredentials. if (amConfig.getLocalResources() != null) { localResources.putAll(amConfig.getLocalResources()); } localResources.putAll(tezJarResources); // emit conf as PB file Configuration finalTezConf = createFinalTezConfForApp(conf, amConfig.getTezConfiguration()); FSDataOutputStream amConfPBOutBinaryStream = null; try { ConfigurationProto.Builder confProtoBuilder = ConfigurationProto.newBuilder(); Iterator> iter = finalTezConf.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); PlanKeyValuePair.Builder kvp = PlanKeyValuePair.newBuilder(); kvp.setKey(entry.getKey()); kvp.setValue(entry.getValue()); confProtoBuilder.addConfKeyValues(kvp); } //binary output amConfPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryConfPath); confProtoBuilder.build().writeTo(amConfPBOutBinaryStream); } finally { if(amConfPBOutBinaryStream != null){ amConfPBOutBinaryStream.close(); } } LocalResource binaryConfLRsrc = TezClientUtils.createLocalResource(fs, binaryConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); // Create Session Jars definition to be sent to AM as a local resource Path sessionJarsPath = TezCommonUtils.getTezSessionJarStagingPath(tezSysStagingPath); FSDataOutputStream sessionJarsPBOutStream = null; try { Map sessionJars = new HashMap(tezJarResources.size() + 1); sessionJars.putAll(tezJarResources); sessionJars.put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); DAGProtos.PlanLocalResourcesProto proto = DagTypeConverters.convertFromLocalResources(sessionJars); sessionJarsPBOutStream = TezCommonUtils.createFileForAM(fs, sessionJarsPath); proto.writeDelimitedTo(sessionJarsPBOutStream); // Write out the initial list of resources which will be available in the AM DAGProtos.PlanLocalResourcesProto amResourceProto; if (amConfig.getLocalResources() != null && !amConfig.getLocalResources().isEmpty()) { amResourceProto = DagTypeConverters.convertFromLocalResources(localResources); } else { amResourceProto = DAGProtos.PlanLocalResourcesProto.getDefaultInstance(); } amResourceProto.writeDelimitedTo(sessionJarsPBOutStream); } finally { if (sessionJarsPBOutStream != null) { sessionJarsPBOutStream.close(); } } LocalResource sessionJarsPBLRsrc = TezClientUtils.createLocalResource(fs, sessionJarsPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); localResources.put( TezConfiguration.TEZ_SESSION_LOCAL_RESOURCES_PB_FILE_NAME, sessionJarsPBLRsrc); if(dag != null) { for (Vertex v : dag.getVertices()) { if (tezJarResources != null) { v.getTaskLocalFiles().putAll(tezJarResources); } v.getTaskLocalFiles().put(TezConfiguration.TEZ_PB_BINARY_CONF_NAME, binaryConfLRsrc); Map taskEnv = v.getTaskEnvironment(); TezYARNUtils.setupDefaultEnv(taskEnv, conf, TezConfiguration.TEZ_TASK_LAUNCH_ENV, TezConfiguration.TEZ_TASK_LAUNCH_ENV_DEFAULT); TezClientUtils.setDefaultLaunchCmdOpts(v, amConfig.getTezConfiguration()); } // emit protobuf DAG file style Path binaryPath = TezCommonUtils.getTezBinPlanStagingPath(tezSysStagingPath); if (LOG.isDebugEnabled()) { LOG.debug("Stage directory information for AppId :" + appId + " tezSysStagingPath :" + tezSysStagingPath + " binaryConfPath :" + binaryConfPath + " sessionJarsPath :" + sessionJarsPath + " binaryPlanPath :" + binaryPath); } amConfig.getTezConfiguration().set(TezConfiguration.TEZ_AM_PLAN_REMOTE_PATH, binaryPath.toUri().toString()); DAGPlan dagPB = dag.createDag(null); FSDataOutputStream dagPBOutBinaryStream = null; try { //binary output dagPBOutBinaryStream = TezCommonUtils.createFileForAM(fs, binaryPath); dagPB.writeTo(dagPBOutBinaryStream); } finally { if(dagPBOutBinaryStream != null){ dagPBOutBinaryStream.close(); } } localResources.put(TezConfiguration.TEZ_PB_PLAN_BINARY_NAME, TezClientUtils.createLocalResource(fs, binaryPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); if (Level.DEBUG.isGreaterOrEqual(Level.toLevel(amLogLevel))) { Path textPath = localizeDagPlanAsText(dagPB, fs, amConfig, strAppId, tezSysStagingPath); localResources.put(TezConfiguration.TEZ_PB_PLAN_TEXT_NAME, TezClientUtils.createLocalResource(fs, textPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); } } Map acls = new HashMap(); // Setup ContainerLaunchContext for AM container ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(localResources, environment, vargsFinal, null, securityTokens, acls); // Set up the ApplicationSubmissionContext ApplicationSubmissionContext appContext = Records .newRecord(ApplicationSubmissionContext.class); appContext.setApplicationType(TezConfiguration.TEZ_APPLICATION_TYPE); appContext.setApplicationId(appId); appContext.setResource(capability); if (amConfig.getQueueName() != null) { appContext.setQueue(amConfig.getQueueName()); } appContext.setApplicationName(amName); appContext.setCancelTokensWhenComplete(amConfig.getTezConfiguration().getBoolean( TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN, TezConfiguration.TEZ_AM_CANCEL_DELEGATION_TOKEN_DEFAULT)); appContext.setAMContainerSpec(amContainer); appContext.setMaxAppAttempts( finalTezConf.getInt(TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS, TezConfiguration.TEZ_AM_MAX_APP_ATTEMPTS_DEFAULT)); return appContext; } static void maybeAddDefaultLoggingJavaOpts(String logLevel, List vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static String maybeAddDefaultLoggingJavaOpts(String logLevel, String javaOpts) { List vargs = new ArrayList(5); if (javaOpts != null) { vargs.add(javaOpts); } else { vargs.add(""); } maybeAddDefaultLoggingJavaOpts(logLevel, vargs); if (vargs.size() == 1) { return vargs.get(0); } return StringUtils.join(vargs, " ").trim(); } static void setDefaultLaunchCmdOpts(Vertex v, TezConfiguration conf) { String vOpts = v.getTaskLaunchCmdOpts(); String vConfigOpts = conf.get(TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS, TezConfiguration.TEZ_TASK_LAUNCH_CMD_OPTS_DEFAULT); if (vConfigOpts != null && vConfigOpts.length() > 0) { vOpts += (" " + vConfigOpts); } vOpts = maybeAddDefaultLoggingJavaOpts(conf.get( TezConfiguration.TEZ_TASK_LOG_LEVEL, TezConfiguration.TEZ_TASK_LOG_LEVEL_DEFAULT), vOpts); v.setTaskLaunchCmdOpts(vOpts); } @Private @VisibleForTesting public static void addLog4jSystemProperties(String logLevel, List vargs) { vargs.add("-Dlog4j.configuration=" + TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE); vargs.add("-D" + YarnConfiguration.YARN_APP_CONTAINER_LOG_DIR + "=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR); vargs.add("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=" + logLevel + "," + TezConfiguration.TEZ_CONTAINER_LOGGER_NAME); } static Configuration createFinalTezConfForApp(TezConfiguration tezConf, TezConfiguration amConf) { Configuration conf = new Configuration(false); conf.setQuietMode(true); assert tezConf != null; assert amConf != null; Entry entry; Iterator> iter = tezConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from conf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } iter = amConf.iterator(); while (iter.hasNext()) { entry = iter.next(); // Copy all tez config parameters. if (entry.getKey().startsWith(TezConfiguration.TEZ_PREFIX)) { conf.set(entry.getKey(), entry.getValue()); if (LOG.isDebugEnabled()) { LOG.debug("Adding tez dag am parameter from amConf: " + entry.getKey() + ", with value: " + entry.getValue()); } } } return conf; } /** * Helper function to create a YARN LocalResource * @param fs FileSystem object * @param p Path of resource to localize * @param type LocalResource Type * @return a YARN LocalResource for the given Path * @throws IOException */ static LocalResource createLocalResource(FileSystem fs, Path p, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { LocalResource rsrc = Records.newRecord(LocalResource.class); FileStatus rsrcStat = fs.getFileStatus(p); rsrc.setResource(ConverterUtils.getYarnUrlFromPath(fs.resolvePath(rsrcStat .getPath()))); rsrc.setSize(rsrcStat.getLen()); rsrc.setTimestamp(rsrcStat.getModificationTime()); rsrc.setType(type); rsrc.setVisibility(visibility); return rsrc; } private static Path localizeDagPlanAsText(DAGPlan dagPB, FileSystem fs, AMConfiguration amConfig, String strAppId, Path tezSysStagingPath) throws IOException { Path textPath = TezCommonUtils.getTezTextPlanStagingPath(tezSysStagingPath); FSDataOutputStream dagPBOutTextStream = null; try { dagPBOutTextStream = TezCommonUtils.createFileForAM(fs, textPath); String dagPBStr = dagPB.toString(); int dagPBStrLen = dagPBStr.length(); if (dagPBStrLen <= UTF8_CHUNK_SIZE) { dagPBOutTextStream.writeUTF(dagPBStr); } else { int startIndex = 0; while (startIndex < dagPBStrLen) { int endIndex = startIndex + UTF8_CHUNK_SIZE; if (endIndex > dagPBStrLen) { endIndex = dagPBStrLen; } dagPBOutTextStream.writeUTF(dagPBStr.substring(startIndex, endIndex)); startIndex += UTF8_CHUNK_SIZE; } } } finally { if (dagPBOutTextStream != null) { dagPBOutTextStream.close(); } } return textPath; } static DAGClientAMProtocolBlockingPB getSessionAMProxy(YarnClient yarnClient, Configuration conf, ApplicationId applicationId) throws TezException, IOException { ApplicationReport appReport; try { appReport = yarnClient.getApplicationReport( applicationId); if(appReport == null) { throw new TezUncheckedException("Could not retrieve application report" + " from YARN, applicationId=" + applicationId); } YarnApplicationState appState = appReport.getYarnApplicationState(); if(appState != YarnApplicationState.RUNNING) { if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.KILLED || appState == YarnApplicationState.FAILED) { throw new SessionNotRunning("Application not running" + ", applicationId=" + applicationId + ", yarnApplicationState=" + appReport.getYarnApplicationState() + ", finalApplicationStatus=" + appReport.getFinalApplicationStatus() + ", trackingUrl=" + appReport.getTrackingUrl()); } return null; } } catch (YarnException e) { throw new TezException(e); } return getAMProxy(conf, appReport.getHost(), appReport.getRpcPort(), appReport.getClientToAMToken()); } @Private public static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken) throws IOException { final InetSocketAddress serviceAddr = new InetSocketAddress(amHost, amRpcPort); UserGroupInformation userUgi = UserGroupInformation.createRemoteUser(UserGroupInformation .getCurrentUser().getUserName()); if (clientToAMToken != null) { Token token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr); userUgi.addToken(token); } if (LOG.isDebugEnabled()) { LOG.debug("Connecting to Tez AM at " + serviceAddr); } DAGClientAMProtocolBlockingPB proxy = null; try { proxy = userUgi.doAs(new PrivilegedExceptionAction() { @Override public DAGClientAMProtocolBlockingPB run() throws IOException { RPC.setProtocolEngine(conf, DAGClientAMProtocolBlockingPB.class, ProtobufRpcEngine.class); return (DAGClientAMProtocolBlockingPB) RPC.getProxy(DAGClientAMProtocolBlockingPB.class, 0, serviceAddr, conf); } }); } catch (InterruptedException e) { throw new IOException("Failed to connect to AM", e); } return proxy; } @Private public static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials) { JobTokenIdentifier identifier = new JobTokenIdentifier(new Text( tokenIdentifier)); Token sessionToken = new Token(identifier, jobTokenSecretManager); sessionToken.setService(identifier.getJobId()); TokenCache.setSessionToken(sessionToken, credentials); } /** * Add computed Xmx value to java opts if both -Xms and -Xmx are not specified * @param javaOpts Current java opts * @param resource Resource capability based on which java opts will be computed * @param maxHeapFactor Factor to size Xmx ( valid range is 0.0 < x < 1.0) * @return Modified java opts with computed Xmx value */ public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } }
blob data class, long method t t f data class, long method blob 0 14549 https://github.com/apache/incubator-tez/blob/e8dc9f72f9d720e5bdf7bb3005d904451a02ce2b/tez-api/src/main/java/org/apache/tez/client/TezClientUtils.java/#L104-L834 1 2462 14549
2437 { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class EndpointDiscoverer, O extends Operation> implements EndpointsSupplier { private final ApplicationContext applicationContext; private final Collection> filters; private final DiscoveredOperationsFactory operationsFactory; private final Map filterEndpoints = new ConcurrentHashMap<>(); private volatile Collection endpoints; /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param filters filters to apply */ public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection invokerAdvisors, Collection> filters) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); Assert.notNull(parameterValueMapper, "ParameterValueMapper must not be null"); Assert.notNull(invokerAdvisors, "InvokerAdvisors must not be null"); Assert.notNull(filters, "Filters must not be null"); this.applicationContext = applicationContext; this.filters = Collections.unmodifiableCollection(filters); this.operationsFactory = getOperationsFactory(parameterValueMapper, invokerAdvisors); } private DiscoveredOperationsFactory getOperationsFactory( ParameterValueMapper parameterValueMapper, Collection invokerAdvisors) { return new DiscoveredOperationsFactory(parameterValueMapper, invokerAdvisors) { @Override protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { return EndpointDiscoverer.this.createOperation(endpointId, operationMethod, invoker); } }; } @Override public final Collection getEndpoints() { if (this.endpoints == null) { this.endpoints = discoverEndpoints(); } return this.endpoints; } private Collection discoverEndpoints() { Collection endpointBeans = createEndpointBeans(); addExtensionBeans(endpointBeans); return convertToEndpoints(endpointBeans); } private Collection createEndpointBeans() { Map byId = new LinkedHashMap<>(); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, Endpoint.class); for (String beanName : beanNames) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { EndpointBean endpointBean = createEndpointBean(beanName); EndpointBean previous = byId.putIfAbsent(endpointBean.getId(), endpointBean); Assert.state(previous == null, () -> "Found two endpoints with the id '" + endpointBean.getId() + "': '" + endpointBean.getBeanName() + "' and '" + previous.getBeanName() + "'"); } } return byId.values(); } private EndpointBean createEndpointBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new EndpointBean(beanName, bean); } private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors( this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { ExtensionBean extensionBean = createExtensionBean(beanName); EndpointBean endpointBean = byId.get(extensionBean.getEndpointId()); Assert.state(endpointBean != null, () -> ("Invalid extension '" + extensionBean.getBeanName() + "': no endpoint found with id '" + extensionBean.getEndpointId() + "'")); addExtensionBean(endpointBean, extensionBean); } } private ExtensionBean createExtensionBean(String beanName) { Object bean = this.applicationContext.getBean(beanName); return new ExtensionBean(beanName, bean); } private void addExtensionBean(EndpointBean endpointBean, ExtensionBean extensionBean) { if (isExtensionExposed(endpointBean, extensionBean)) { Assert.state( isEndpointExposed(endpointBean) || isEndpointFiltered(endpointBean), () -> "Endpoint bean '" + endpointBean.getBeanName() + "' cannot support the extension bean '" + extensionBean.getBeanName() + "'"); endpointBean.addExtension(extensionBean); } } private Collection convertToEndpoints(Collection endpointBeans) { Set endpoints = new LinkedHashSet<>(); for (EndpointBean endpointBean : endpointBeans) { if (isEndpointExposed(endpointBean)) { endpoints.add(convertToEndpoint(endpointBean)); } } return Collections.unmodifiableSet(endpoints); } private E convertToEndpoint(EndpointBean endpointBean) { MultiValueMap indexed = new LinkedMultiValueMap<>(); EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { String extensionBeans = endpointBean.getExtensions().stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } for (ExtensionBean extensionBean : endpointBean.getExtensions()) { addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); List operations = indexed.values().stream().map(this::getLast) .filter(Objects::nonNull).collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } private void addOperations(MultiValueMap indexed, EndpointId id, Object target, boolean replaceLast) { Set replacedLast = new HashSet<>(); Collection operations = this.operationsFactory.createOperations(id, target); for (O operation : operations) { OperationKey key = createOperationKey(operation); O last = getLast(indexed.get(key)); if (replaceLast && replacedLast.add(key) && last != null) { indexed.get(key).remove(last); } indexed.add(key, operation); } } private T getLast(List list) { return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1); } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { List duplicates = indexed.entrySet().stream() .filter((entry) -> entry.getValue().size() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); String extensionBeanNames = extensions.stream() .map(ExtensionBean::getBeanName).collect(Collectors.joining(", ")); throw new IllegalStateException( "Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); } } private boolean isExtensionExposed(EndpointBean endpointBean, ExtensionBean extensionBean) { return isFilterMatch(extensionBean.getFilter(), endpointBean) && isExtensionExposed(extensionBean.getBean()); } /** * Determine if an extension bean should be exposed. Subclasses can override this * method to provide additional logic. * @param extensionBean the extension bean * @return {@code true} if the extension is exposed */ protected boolean isExtensionExposed(Object extensionBean) { return true; } private boolean isEndpointExposed(EndpointBean endpointBean) { return isFilterMatch(endpointBean.getFilter(), endpointBean) && !isEndpointFiltered(endpointBean) && isEndpointExposed(endpointBean.getBean()); } /** * Determine if an endpoint bean should be exposed. Subclasses can override this * method to provide additional logic. * @param endpointBean the endpoint bean * @return {@code true} if the endpoint is exposed */ protected boolean isEndpointExposed(Object endpointBean) { return true; } private boolean isEndpointFiltered(EndpointBean endpointBean) { for (EndpointFilter filter : this.filters) { if (!isFilterMatch(filter, endpointBean)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isFilterMatch(Class filter, EndpointBean endpointBean) { if (!isEndpointExposed(endpointBean.getBean())) { return false; } if (filter == null) { return true; } E endpoint = getFilterEndpoint(endpointBean); Class generic = ResolvableType.forClass(EndpointFilter.class, filter) .resolveGeneric(0); if (generic == null || generic.isInstance(endpoint)) { EndpointFilter instance = (EndpointFilter) BeanUtils .instantiateClass(filter); return isFilterMatch(instance, endpoint); } return false; } private boolean isFilterMatch(EndpointFilter filter, EndpointBean endpointBean) { return isFilterMatch(filter, getFilterEndpoint(endpointBean)); } @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) .withLogger(EndpointDiscoverer.class).invokeAnd((f) -> f.match(endpoint)) .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { E endpoint = this.filterEndpoints.get(endpointBean); if (endpoint == null) { endpoint = createEndpoint(endpointBean.getBean(), endpointBean.getId(), endpointBean.isEnabledByDefault(), Collections.emptySet()); this.filterEndpoints.put(endpointBean, endpoint); } return endpoint; } @SuppressWarnings("unchecked") protected Class getEndpointType() { return (Class) ResolvableType .forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean * @param id the ID of the endpoint * @param enabledByDefault if the endpoint is enabled by default * @param operations the endpoint operations * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) */ protected abstract E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. * @param endpointId the endpoint id * @param operationMethod the operation method * @param invoker the invoker to use * @return a created operation */ protected abstract O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. * @param operation the source operation * @return the operation key */ protected abstract OperationKey createOperationKey(O operation); /** * A key generated for an {@link Operation} based on specific criteria from the actual * operation implementation. */ protected static final class OperationKey { private final Object key; private final Supplier description; /** * Create a new {@link OperationKey} instance. * @param key the underlying key for the operation * @param description a human readable description of the key */ public OperationKey(Object key, Supplier description) { Assert.notNull(key, "Key must not be null"); Assert.notNull(description, "Description must not be null"); this.key = key; this.description = description; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.key.equals(((OperationKey) obj).key); } @Override public int hashCode() { return this.key.hashCode(); } @Override public String toString() { return this.description.get(); } } /** * Information about an {@link Endpoint @Endpoint} bean. */ private static class EndpointBean { private final String beanName; private final Object bean; private final EndpointId id; private boolean enabledByDefault; private final Class filter; private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { AnnotationAttributes attributes = AnnotatedElementUtils .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, true); String id = attributes.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + bean.getClass().getName()); this.beanName = beanName; this.bean = bean; this.id = EndpointId.of(id); this.enabledByDefault = (Boolean) attributes.get("enableByDefault"); this.filter = getFilter(this.bean.getClass()); } public void addExtension(ExtensionBean extensionBean) { this.extensions.add(extensionBean); } public Set getExtensions() { return this.extensions; } private Class getFilter(Class type) { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(type, FilteredEndpoint.class); if (attributes == null) { return null; } return attributes.getClass("value"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getId() { return this.id; } public boolean isEnabledByDefault() { return this.enabledByDefault; } public Class getFilter() { return this.filter; } } /** * Information about an {@link EndpointExtension EndpointExtension} bean. */ private static class ExtensionBean { private final String beanName; private final Object bean; private final EndpointId endpointId; private final Class filter; ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(bean.getClass(), EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); AnnotationAttributes endpointAttributes = AnnotatedElementUtils .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true); Assert.state(endpointAttributes != null, () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.getClass("filter"); } public String getBeanName() { return this.beanName; } public Object getBean() { return this.bean; } public EndpointId getEndpointId() { return this.endpointId; } public Class getFilter() { return this.filter; } } }
blob 1. data class t t f 1. data class blob 0 14471 https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java/#L67-L532 1 2437 14471
1241    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } }
feature envy long method, data class t t f long method, data class feature envy 0 10410 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 1 1241 10410
805 {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class", "Blob"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } }
blob long method, data class, blob t t t long method, data class   0 7623 https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 1 805 7623
2384   YES I found bad smells. The bad smells are: 1.Long method 2.Missing JavaDoc 3.Magic numbers 4.Large class 5.Data class I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } }
blob Long method2Missing JavaDoc3Magic numbers4Large class5Data class t f f .Long method2.Missing JavaDoc3.Magic numbers4.Large class5.Data class blob 0 14343 https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 2 2384 14343
1705 {"answer": "YES I found bad smells", "the bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } }
blob data class t t f data class blob 0 11749 https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 1 1705 11749
963   { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; }
long method long method, data class t t t  data class   0 8574 https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 1 963 8574
561      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); }
long method long method, data class t t t  data class   0 5662 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 1 561 5662
717    { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } }
long method long method, data class t t t  data class   0 6826 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 1 717 6826
575    { "output": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; }
long method data class, long method t t t data class   0 5777 https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 1 575 5777
212  {"message":"YES I found bad smells","bad_smells":["1. Long Method","2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ReportOSGiLaunchDelegate extends EclipseApplicationLaunchConfiguration implements IReportLaunchConstants { ReportLaunchHelper helper; public static final String APP_NAME = "application name";//$NON-NLS-1$ public ReportOSGiLaunchDelegate( ) { helper = new ReportLaunchHelper( ); } public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor ) throws CoreException { helper.init( configuration ); super.launch( configuration, mode, launch, monitor ); } public String[] getVMArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getVMArguments( configuration ); List arguments = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { arguments.add( args[i] ); } helper.addPortArgs( arguments ); helper.addUserClassPath( arguments, configuration ); helper.addFileNameArgs( arguments ); helper.addEngineHomeArgs( arguments ); helper.addResourceFolder( arguments ); helper.addTempFolder( arguments ); helper.addTypeArgs( arguments ); helper.addDataLimitArgs(arguments); helper.addParameterArgs( arguments ); return (String[]) arguments.toArray( new String[arguments.size( )] ); } public String[] getProgramArguments( ILaunchConfiguration configuration ) throws CoreException { String[] args = super.getProgramArguments( configuration ); List list = new ArrayList( ); for ( int i = 0; i < args.length; i++ ) { list.add( args[i] ); } int idx = list.indexOf( "-application" ); //$NON-NLS-1$ if ( idx != -1 && ( idx + 1 ) < list.size( ) ) { list.set( idx + 1, getApplicationName( ) ); //$NON-NLS-1$ } else { list.add( "-application" ); //$NON-NLS-1$ list.add( getApplicationName( ) ); //$NON-NLS-1$ } list.add( "-nosplash" ); //$NON-NLS-1$ return (String[]) list.toArray( new String[list.size( )] ); } private String getApplicationName() { String name = System.getProperty( APP_NAME ); if (name == null || name.length( ) == 0) { name = "org.eclipse.birt.report.debug.core.ReportDebugger"; } return name; } public IVMRunner getVMRunner( ILaunchConfiguration configuration, String mode ) throws CoreException { if ( ( helper.debugType & DEBUG_TYPE_JAVA_CLASS ) == DEBUG_TYPE_JAVA_CLASS ) { mode = ILaunchManager.DEBUG_MODE; } else { mode = ILaunchManager.RUN_MODE; } return new ReportDebuggerVMRunner( super.getVMRunner( configuration, mode ), ( helper.debugType & DEBUG_TYPE_JAVA_SCRIPT ) == DEBUG_TYPE_JAVA_SCRIPT, this ); } protected IProject[] getBuildOrder( ILaunchConfiguration configuration, String mode ) throws CoreException { return super.getBuildOrder( configuration, mode ); } public boolean finalLaunchCheck( final ILaunchConfiguration configuration, String mode, IProgressMonitor monitor ) throws CoreException { boolean bool = super.finalLaunchCheck( configuration, mode, monitor ); if ( !bool ) { return bool; } return helper.finalLaunchCheck( configuration, mode, monitor ); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 2323 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportOSGiLaunchDelegate.java/#L30-L153 1 212 2323
2071 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } }
long method data class t t f data class long method 0 13025 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 1 2071 13025
1794  {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } }
blob Data Class, Long Method t f f Data Class, Long Method blob 0 11997 https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 1 1794 11997
2193         { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } }
long method 1. long method, 2. data class t t t  2. data class   0 13477 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 1 2193 13477
2205  YES, I found bad smells the bad smells are: 1. Long method 2. Inappropriate inheritance 3. Primitive obsession 4. Feature envy 5. Data class 6. Hashcode and equals not overridden in superclass I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } }
blob  Long method 2 Inappropriate inheritance 3 Primitive obsession 4 Feature envy 5 Data class 6 Hashcode and equals not overridden in superclass t f f . Long method 2. Inappropriate inheritance 3. Primitive obsession 4. Feature envy 5. Data class 6. Hashcode and equals not overridden in superclass blob 0 13511 https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 2 2205 13511
1921 {"response": "YES I found bad smells the bad smells are: 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } }
blob 2. data class t t f 2. data class blob 0 12424 https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 1 1921 12424
2658      { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); }
feature envy long method, data class t t f long method, data class feature envy 0 15186 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 1 2658 15186
47          { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class BaseDeclProcessor { /** * Resolves relative URIs in the supplied query model using either the specified externalBaseURI or, if * this parameter is null, the base URI specified in the query model itself. * * @param qc The query model to resolve relative URIs in. * @param externalBaseURI The external base URI to use for resolving relative URIs, or null if the base URI * that is specified in the query model should be used. * @throws IllegalArgumentException If an external base URI is specified that is not an absolute URI. * @throws MalformedQueryException If the base URI specified in the query model is not an absolute URI. */ public static void process(ASTOperationContainer qc, String externalBaseURI) throws MalformedQueryException { ParsedIRI parsedBaseURI = null; // Use the query model's own base URI, if available ASTBaseDecl baseDecl = qc.getBaseDecl(); if (baseDecl != null) { try { parsedBaseURI = new ParsedIRI(baseDecl.getIRI()); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new MalformedQueryException("BASE IRI is not an absolute IRI: " + externalBaseURI); } } else if (externalBaseURI != null) { // Use external base URI if the query doesn't contain one itself try { parsedBaseURI = new ParsedIRI(externalBaseURI); } catch (URISyntaxException e) { throw new MalformedQueryException(e); } if (!parsedBaseURI.isAbsolute()) { throw new IllegalArgumentException("Supplied base URI is not an absolute IRI: " + externalBaseURI); } } else { // FIXME: use the "Default Base URI"? } if (parsedBaseURI != null) { ASTUnparsedQuadDataBlock dataBlock = null; if (qc.getOperation() instanceof ASTInsertData) { ASTInsertData insertData = (ASTInsertData) qc.getOperation(); dataBlock = insertData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } else if (qc.getOperation() instanceof ASTDeleteData) { ASTDeleteData deleteData = (ASTDeleteData) qc.getOperation(); dataBlock = deleteData.jjtGetChild(ASTUnparsedQuadDataBlock.class); } if (dataBlock != null) { final String baseURIDeclaration = "BASE <" + parsedBaseURI + "> \n"; dataBlock.setDataBlock(baseURIDeclaration + dataBlock.getDataBlock()); } else { RelativeIRIResolver visitor = new RelativeIRIResolver(parsedBaseURI); try { qc.jjtAccept(visitor, null); } catch (VisitorException e) { throw new MalformedQueryException(e); } } } } private static class RelativeIRIResolver extends AbstractASTVisitor { private ParsedIRI parsedBaseURI; public RelativeIRIResolver(ParsedURI parsedBaseURI) { this(ParsedIRI.create(parsedBaseURI.toString())); } public RelativeIRIResolver(ParsedIRI parsedBaseURI) { this.parsedBaseURI = parsedBaseURI; } @Override public Object visit(ASTIRI node, Object data) throws VisitorException { node.setValue(parsedBaseURI.resolve(node.getValue())); return super.visit(node, data); } @Override public Object visit(ASTIRIFunc node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } @Override public Object visit(ASTServiceGraphPattern node, Object data) throws VisitorException { node.setBaseURI(parsedBaseURI.toString()); return super.visit(node, data); } } }
blob long method, data class t t f long method, data class blob 0 840 https://github.com/eclipse/rdf4j/blob/6f63df540e30b28e0c8880bea72f85cb88424b03/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/BaseDeclProcessor.java/#L31-L129 1 47 840
769 { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long method", "2. Data class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 7259 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 1 769 7259
1762  {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11892 https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 1 1762 11892
1159  { "answer": "YES, I found bad smells", "bad_smells": [ "1. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } }
blob 1. data class t t f 1. data class blob 0 10159 https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 1 1159 10159
2093      { "answer": "YES I found bad smells", "bad smells are": [ "1. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component("aws-ddbstream") public class DdbStreamComponent extends DefaultComponent { @Metadata private String accessKey; @Metadata private String secretKey; @Metadata private String region; @Metadata(label = "advanced") private DdbStreamConfiguration configuration; public DdbStreamComponent() { this(null); } public DdbStreamComponent(CamelContext context) { super(context); this.configuration = new DdbStreamConfiguration(); registerExtension(new DdbStreamComponentVerifierExtension()); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { DdbStreamConfiguration configuration = this.configuration.copy(); configuration.setTableName(remaining); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Table name must be specified."); } configuration.setTableName(remaining); if (ObjectHelper.isEmpty(configuration.getAccessKey())) { setAccessKey(accessKey); } if (ObjectHelper.isEmpty(configuration.getSecretKey())) { setSecretKey(secretKey); } if (ObjectHelper.isEmpty(configuration.getRegion())) { setRegion(region); } if (configuration.getAmazonDynamoDbStreamsClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("amazonDDBStreamsClient or accessKey and secretKey must be specified"); } DdbStreamEndpoint endpoint = new DdbStreamEndpoint(uri, configuration, this); setProperties(endpoint, parameters); return endpoint; } public DdbStreamConfiguration getConfiguration() { return configuration; } /** * The AWS DDB stream default configuration */ public void setConfiguration(DdbStreamConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return configuration.getAccessKey(); } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { configuration.setAccessKey(accessKey); } public String getSecretKey() { return configuration.getSecretKey(); } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { configuration.setSecretKey(secretKey); } public String getRegion() { return configuration.getRegion(); } /** * Amazon AWS Region */ public void setRegion(String region) { configuration.setRegion(region); } }
blob 1. data class t t f 1. data class blob 0 13140 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamComponent.java/#L28-L122 1 2093 13140
1517 {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Repository public class UserDao { private static final String DEFAULT_USER_CREDENTIALS_PROPERTIES = "users-credentials.properties"; private static final Logger LOG = LoggerFactory.getLogger(UserDao.class); private Properties userLogins; @PostConstruct public void init() { loadFileLoginsDetails(); } void loadFileLoginsDetails() { InputStream inStr = null; try { Configuration configuration = ApplicationProperties.get(); inStr = ApplicationProperties.getFileAsInputStream(configuration, "atlas.authentication.method.file.filename", DEFAULT_USER_CREDENTIALS_PROPERTIES); userLogins = new Properties(); userLogins.load(inStr); } catch (IOException | AtlasException e) { LOG.error("Error while reading user.properties file", e); throw new RuntimeException(e); } finally { if(inStr != null) { try { inStr.close(); } catch(Exception excp) { // ignore } } } } public User loadUserByUsername(final String username) throws AuthenticationException { String userdetailsStr = userLogins.getProperty(username); if (userdetailsStr == null || userdetailsStr.isEmpty()) { throw new UsernameNotFoundException("Username not found." + username); } String password = ""; String role = ""; String dataArr[] = userdetailsStr.split("::"); if (dataArr != null && dataArr.length == 2) { role = dataArr[0]; password = dataArr[1]; } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } List grantedAuths = new ArrayList<>(); if (StringUtils.hasText(role)) { grantedAuths.add(new SimpleGrantedAuthority(role)); } else { LOG.error("User role credentials is not set properly for {}", username); throw new AtlasAuthenticationException("User role credentials is not set properly for " + username ); } User userDetails = new User(username, password, grantedAuths); return userDetails; } @VisibleForTesting public void setUserLogins(Properties userLogins) { this.userLogins = userLogins; } public static String getSha256Hash(String base) throws AtlasAuthenticationException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff & aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (Exception ex) { throw new AtlasAuthenticationException("Exception while encoding password.", ex); } } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11166 https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/dao/UserDao.java/#L44-L135 1 1517 11166
1970      { "output": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } }
long method Long Method, Data Class t f t  Data Class   0 12607 https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 1 1970 12607
1493 {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } }
feature envy long method, data class t t f long method, data class feature envy 0 11121 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 1 1493 11121
423       { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; }
long method long method, data class t t t  data class   0 4247 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 1 423 4247
2523 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); }
long method long method, data class t t t  data class   0 14713 https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 1 2523 14713
479  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class AbstractRecipientRewriteTable implements RecipientRewriteTable, Configurable { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRecipientRewriteTable.class); // The maximum mappings which will process before throwing exception private int mappingLimit = 10; private boolean recursive = true; private DomainList domainList; @Inject public void setDomainList(DomainList domainList) { this.domainList = domainList; } @Override public void configure(HierarchicalConfiguration config) throws ConfigurationException { setRecursiveMapping(config.getBoolean("recursiveMapping", true)); try { setMappingLimit(config.getInt("mappingLimit", 10)); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage()); } doConfigure(config); } /** * Override to handle config */ protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException { } public void setRecursiveMapping(boolean recursive) { this.recursive = recursive; } /** * Set the mappingLimit * * @param mappingLimit * the mappingLimit * @throws IllegalArgumentException * get thrown if mappingLimit smaller then 1 is used */ public void setMappingLimit(int mappingLimit) throws IllegalArgumentException { if (mappingLimit < 1) { throw new IllegalArgumentException("The minimum mappingLimit is 1"); } this.mappingLimit = mappingLimit; } @Override public Mappings getResolvedMappings(String user, Domain domain) throws ErrorMappingException, RecipientRewriteTableException { return getMappings(User.fromLocalPartWithDomain(user, domain), mappingLimit); } private Mappings getMappings(User user, int mappingLimit) throws ErrorMappingException, RecipientRewriteTableException { // We have to much mappings throw ErrorMappingException to avoid // infinity loop if (mappingLimit == 0) { throw new TooManyMappingException("554 Too many mappings to process"); } Mappings targetMappings = mapAddress(user.getLocalPart(), user.getDomainPart().get()); try { return MappingsImpl.fromMappings( targetMappings.asStream() .flatMap(Throwing.function((Mapping target) -> convertAndRecurseMapping(user, target, mappingLimit)).sneakyThrow())); } catch (SkipMappingProcessingException e) { return MappingsImpl.empty(); } } private Stream convertAndRecurseMapping(User originalUser, Mapping associatedMapping, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException, SkipMappingProcessingException, AddressException { Function> convertAndRecurseMapping = Throwing .function((User rewrittenUser) -> convertAndRecurseMapping(associatedMapping, originalUser, rewrittenUser, remainingLoops)) .sneakyThrow(); return associatedMapping.rewriteUser(originalUser) .map(rewrittenUser -> rewrittenUser.withDefaultDomainFromUser(originalUser)) .map(convertAndRecurseMapping) .orElse(Stream.empty()); } private Stream convertAndRecurseMapping(Mapping mapping, User originalUser, User rewrittenUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { LOGGER.debug("Valid virtual user mapping {} to {}", originalUser.asString(), rewrittenUser.asString()); Stream nonRecursiveResult = Stream.of(toMapping(rewrittenUser, mapping.getType())); if (!recursive) { return nonRecursiveResult; } // Check if the returned mapping is the same as the input. If so we need to handle identity to avoid loops. if (originalUser.equals(rewrittenUser)) { return mapping.handleIdentity(nonRecursiveResult); } else { return recurseMapping(nonRecursiveResult, rewrittenUser, remainingLoops); } } private Stream recurseMapping(Stream nonRecursiveResult, User targetUser, int remainingLoops) throws ErrorMappingException, RecipientRewriteTableException { Mappings childMappings = getMappings(targetUser, remainingLoops - 1); if (childMappings.isEmpty()) { return nonRecursiveResult; } else { return childMappings.asStream(); } } private Mapping toMapping(User rewrittenUser, Type type) { switch (type) { case Forward: case Group: case Alias: return Mapping.of(type, rewrittenUser.asString()); case Regex: case Domain: case Error: case Address: return Mapping.address(rewrittenUser.asString()); } throw new IllegalArgumentException("unhandled enum type"); } @Override public void addRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { try { Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new RecipientRewriteTableException("Invalid regex: " + regex, e); } Mapping mapping = Mapping.regex(regex); checkDuplicateMapping(source, mapping); LOGGER.info("Add regex mapping => {} for source {}", regex, source.asString()); addMapping(source, mapping); } @Override public void removeRegexMapping(MappingSource source, String regex) throws RecipientRewriteTableException { LOGGER.info("Remove regex mapping => {} for source: {}", regex, source.asString()); removeMapping(source, Mapping.regex(regex)); } @Override public void addAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add address mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } private Domain defaultDomain() throws RecipientRewriteTableException { try { return domainList.getDefaultDomain(); } catch (DomainListException e) { throw new RecipientRewriteTableException("Unable to retrieve default domain", e); } } private void checkHasValidAddress(Mapping mapping) throws RecipientRewriteTableException { if (!mapping.asMailAddress().isPresent()) { throw new RecipientRewriteTableException("Invalid emailAddress: " + mapping.asString()); } } @Override public void removeAddressMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.address(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove address mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { Mapping mapping = Mapping.error(error); checkDuplicateMapping(source, mapping); LOGGER.info("Add error mapping => {} for source: {}", error, source.asString()); addMapping(source, mapping); } @Override public void removeErrorMapping(MappingSource source, String error) throws RecipientRewriteTableException { LOGGER.info("Remove error mapping => {} for source: {}", error, source.asString()); removeMapping(source, Mapping.error(error)); } @Override public void addAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Add domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); addMapping(source, Mapping.domain(realDomain)); } @Override public void removeAliasDomainMapping(MappingSource source, Domain realDomain) throws RecipientRewriteTableException { LOGGER.info("Remove domain mapping: {} => {}", source.asDomain().map(Domain::asString).orElse("null"), realDomain); removeMapping(source, Mapping.domain(realDomain)); } @Override public void addForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add forward mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeForwardMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.forward(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove forward mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); LOGGER.info("Add group mapping => {} for source: {}", mapping.asString(), source.asString()); addMapping(source, mapping); } @Override public void removeGroupMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.group(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove group mapping => {} for source: {}", mapping.asString(), source.asString()); removeMapping(source, mapping); } @Override public void addAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); checkHasValidAddress(mapping); checkDuplicateMapping(source, mapping); checkNotSameSourceAndDestination(source, address); LOGGER.info("Add alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); addMapping(source, mapping); } @Override public void removeAliasMapping(MappingSource source, String address) throws RecipientRewriteTableException { Mapping mapping = Mapping.alias(address) .appendDomainFromThrowingSupplierIfNone(this::defaultDomain); LOGGER.info("Remove alias source => {} for destination mapping: {}", source.asString(), mapping.asString()); removeMapping(source, mapping); } /** * Return a Map which holds all Mappings * * @return Map */ public abstract Map getAllMappings() throws RecipientRewriteTableException; /** * This method must return stored Mappings for the given user. * It must never return null but throw RecipientRewriteTableException on errors and return an empty Mappings * object if no mapping is found. */ protected abstract Mappings mapAddress(String user, Domain domain) throws RecipientRewriteTableException; private void checkDuplicateMapping(MappingSource source, Mapping mapping) throws RecipientRewriteTableException { Mappings mappings = getStoredMappings(source); if (mappings.contains(mapping)) { throw new MappingAlreadyExistsException("Mapping " + mapping.asString() + " for " + source.asString() + " already exist!"); } } private void checkNotSameSourceAndDestination(MappingSource source, String address) throws RecipientRewriteTableException { if (source.asMailAddress().map(mailAddress -> mailAddress.asString().equals(address)).orElse(false)) { throw new SameSourceAndDestinationException("Source and destination can't be the same!"); } } }
blob long method, data class t t f long method, data class blob 0 4625 https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/data/data-library/src/main/java/org/apache/james/rrt/lib/AbstractRecipientRewriteTable.java/#L47-L351 1 479 4625
271  { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } }
blob data class t t f data class blob 0 2918 https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 1 271 2918
2459      { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface ExternalLoadBalancerDeviceManager extends Manager { public static final int DEFAULT_LOAD_BALANCER_CAPACITY = 50; /** * adds a load balancer device in to a physical network * @param physicalNetworkId physical network id of the network in to which device to be added * @param url url encoding device IP and device configuration parameter * @param username username * @param password password * @param deviceName device name * @param server resource that will handle the commands specific to this device * @return Host object for the device added */ public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource, boolean gslbProvider, boolean exclusiveGslbProvider, String gslbSitePublicIp, String gslbSitePrivateIp); /** * deletes load balancer device added in to a physical network * @param hostId * @return true if device successfully deleted */ public boolean deleteExternalLoadBalancer(long hostId); /** * list external load balancers of given device name type added in to a physical network * @param physicalNetworkId * @param deviceName * @return list of host objects for the external load balancers added in to the physical network */ public List listExternalLoadBalancers(long physicalNetworkId, String deviceName); /** * finds a suitable load balancer device which can be used by this network * @param network guest network * @param dedicatedLb true if a dedicated load balancer is needed for this guest network * @return ExternalLoadBalancerDeviceVO corresponding to the suitable device * @throws InsufficientCapacityException */ public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException; /** * returns the load balancer device allocated for the guest network * @param network guest network id * @return ExternalLoadBalancerDeviceVO object corresponding the load balancer device assigned for this guest network */ public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network); /** * applies load balancer rules * @param network guest network if * @param rules load balancer rules * @return true if successfully applied rules * @throws ResourceUnavailableException */ public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; /** * implements or shutdowns guest network on the load balancer device assigned to the guest network * @param add * @param guestConfig * @return * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; public List getLBHealthChecks(Network network, List rules) throws ResourceUnavailableException; }
blob long method, data class t t f long method, data class blob 0 14536 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManager.java/#L35-L103 1 2459 14536
849 { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
final class SearchFirstStringNode extends Node { private static final int[] UNINTIALIZED_CACHED_INDICES = new int[0]; private final VectorLengthProfile targetLengthProfile = VectorLengthProfile.create(); private final VectorLengthProfile elementsLengthProfile = VectorLengthProfile.create(); private final ValueProfile targetClassProfile = ValueProfile.createClassProfile(); private final ValueProfile elementsClassProfile = ValueProfile.createClassProfile(); @Child private StringEqualsNode stringEquals = CompareStringNode.createEquals(); @Child private CompareStringNode stringStartsWith; @Child private StringEqualsNode equalsDuplicate; private final NACheck elementsNACheck = NACheck.create(); private final NACheck targetNACheck = NACheck.create(); private final BranchProfile everFoundDuplicate = BranchProfile.create(); private final BranchProfile seenInvalid = BranchProfile.create(); /** Instead of using the notFoundStartIndex we use NA. */ private final boolean useNAForNotFound; private final boolean exactMatch; @CompilationFinal(dimensions = 1) private int[] cachedIndices; private SearchFirstStringNode(boolean exactMatch, boolean useNAForNotFound) { this.exactMatch = exactMatch; this.useNAForNotFound = useNAForNotFound; if (!exactMatch) { stringStartsWith = CompareStringNode.createStartsWith(); } } public RAbstractIntVector apply(RAbstractStringVector target, RAbstractStringVector elements, int notFoundStartIndex, RStringVector names) { RAbstractStringVector targetProfiled = targetClassProfile.profile(target); RAbstractStringVector elementsProfiled = elementsClassProfile.profile(elements); int targetLength = targetLengthProfile.profile(targetProfiled.getLength()); int elementsLength = elementsLengthProfile.profile(elementsProfiled.getLength()); targetNACheck.enable(target); elementsNACheck.enable(elements); if (cachedIndices == UNINTIALIZED_CACHED_INDICES) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = searchCached(targetProfiled, targetLength, elementsProfiled, elementsLength, names); } if (cachedIndices != null) { if (!isCacheValid(targetProfiled, targetLength, elementsProfiled, elementsLength, cachedIndices)) { CompilerDirectives.transferToInterpreterAndInvalidate(); cachedIndices = null; // set to generic // fallthrough to generic } else { assert sameVector(searchCached(target, targetLength, elements, elementsLength, names), cachedIndices); return RDataFactory.createIntVector(cachedIndices, true, names); } } return searchGeneric(targetProfiled, targetLength, elementsProfiled, elementsLength, notFoundStartIndex, false, names); } public static SearchFirstStringNode createNode(boolean exactMatch, boolean useNAForNotFound) { return new SearchFirstStringNode(exactMatch, useNAForNotFound); } private int[] searchCached(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, RStringVector names) { if (exactMatch) { RAbstractIntVector genericResult = searchGeneric(target, targetLength, elements, elementsLength, -1, true, names); if (genericResult != null) { return genericResult.materialize().getReadonlyData(); } } return null; } private boolean isCacheValid(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int[] cached) { int cachedLength = cached.length; if (elementsLength != cachedLength) { seenInvalid.enter(); return false; } for (int i = 0; i < cachedLength; i++) { int cachedIndex = cached[i]; String cachedElement = elements.getDataAt(i); int cachedElementHash = cachedElement.hashCode(); assert !elementsNACheck.check(cachedElement) && cachedElement.length() > 0; int cachedTranslatedIndex = cachedIndex - 1; for (int j = 0; j < cachedTranslatedIndex; j++) { String targetString = target.getDataAt(j); if (!targetNACheck.check(targetString) && stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } if (cachedTranslatedIndex < targetLength) { String targetString = target.getDataAt(cachedTranslatedIndex); if (!targetNACheck.check(targetString) && !stringEquals.executeCompare(cachedElement, cachedElementHash, targetString)) { seenInvalid.enter(); return false; } } else { seenInvalid.enter(); return false; } } return true; } private static boolean sameVector(int[] a, int[] b) { if (a == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } private final BranchProfile notFoundProfile = BranchProfile.create(); private final ConditionProfile hashingProfile = ConditionProfile.createBinaryProfile(); private RAbstractIntVector searchGeneric(RAbstractStringVector target, int targetLength, RAbstractStringVector elements, int elementsLength, int notFoundStartIndex, boolean nullOnNotFound, RStringVector names) { int[] indices = new int[elementsLength]; boolean resultComplete = true; long hashingCost = targetLength * 10L + 10 /* constant overhead */; long lookupCost = elementsLength * 2L; long nestedLoopCost = targetLength * (long) elementsLength; NonRecursiveHashMapCharacter map; if (hashingProfile.profile(nestedLoopCost > hashingCost + lookupCost)) { map = new NonRecursiveHashMapCharacter(targetLength); for (int i = 0; i < targetLength; i++) { String name = target.getDataAt(i); if (!targetNACheck.check(name)) { map.put(name, i); } } } else { map = null; } int notFoundIndex = notFoundStartIndex; for (int i = 0; i < elementsLength; i++) { String element = elements.getDataAt(i); boolean isElementNA = elementsNACheck.check(element) || element.length() == 0; if (!isElementNA) { int index; if (map != null) { index = map.get(element); if (!exactMatch && index < 0) { // the map is only good for exact matches index = findNonExactIndex(target, targetLength, element); } } else { index = findIndex(target, targetLength, element); } if (index >= 0) { indices[i] = index + 1; continue; } } notFoundProfile.enter(); if (nullOnNotFound) { return null; } else { int prevDuplicateIndex = -1; if (!isElementNA) { prevDuplicateIndex = findFirstDuplicate(elements, element, i); } int nextIndex; if (prevDuplicateIndex == -1) { if (useNAForNotFound) { resultComplete = false; nextIndex = RRuntime.INT_NA; } else { nextIndex = ++notFoundIndex; } } else { nextIndex = indices[prevDuplicateIndex]; } indices[i] = nextIndex; } } return RDataFactory.createIntVector(indices, resultComplete && elements.isComplete(), names); } private int findNonExactIndex(RAbstractStringVector target, int targetLength, String element) { assert !exactMatch; int nonExactIndex = -1; for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { return -1; } } } } return nonExactIndex; } private int findIndex(RAbstractStringVector target, int targetLength, String element) { int nonExactIndex = -1; int elementHash = element.hashCode(); for (int j = 0; j < targetLength; j++) { String targetValue = target.getDataAt(j); if (!targetNACheck.check(targetValue)) { if (stringEquals.executeCompare(element, elementHash, targetValue)) { return j; } if (!exactMatch) { if (stringStartsWith.executeCompare(targetValue, element)) { if (nonExactIndex == -1) { nonExactIndex = j; } else { nonExactIndex = -2; } } } } } return nonExactIndex; } private int findFirstDuplicate(RAbstractStringVector elements, String element, int currentIndex) { if (equalsDuplicate == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); equalsDuplicate = insert(CompareStringNode.createEquals()); } int elementHash = element.hashCode(); for (int j = 0; j < currentIndex; j++) { String otherElement = elements.getDataAt(j); if (!targetNACheck.check(otherElement) && equalsDuplicate.executeCompare(element, elementHash, otherElement)) { everFoundDuplicate.enter(); return j; } } return -1; } abstract static class CompareStringNode extends Node { public abstract boolean executeCompare(String a, String b); public static StringEqualsNode createEquals() { return new StringEqualsNode(); } public static StringStartsWithNode createStartsWith() { return new StringStartsWithNode(); } public static class StringEqualsNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); private final ConditionProfile hashEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(a.hashCode() != b.hashCode())) { return false; } return a.equals(b); } } public final boolean executeCompare(String a, int aHash, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { if (hashEquals.profile(aHash != b.hashCode())) { return false; } return a.equals(b); } } } private static class StringStartsWithNode extends CompareStringNode { private final ConditionProfile identityEquals = ConditionProfile.createBinaryProfile(); @Override public final boolean executeCompare(String a, String b) { assert !RRuntime.isNA(a); assert !RRuntime.isNA(b); if (identityEquals.profile(Utils.fastPathIdentityEquals(a, b))) { return true; } else { return a.startsWith(b); } } } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 7848 https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/SearchFirstStringNode.java/#L46-L361 1 849 7848
2501    { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class AbstractClientProvider { public AbstractClientProvider() { } /** * Generates a fixed format of application tags given one or more of * application name, version and description. This allows subsequent query for * an application with a name only, version only or description only or any * combination of those as filters. * * @param appName name of the application * @param appVersion version of the application * @param appDescription brief description of the application * @return */ public static final Set createApplicationTags(String appName, String appVersion, String appDescription) { Set tags = new HashSet<>(); tags.add(ServiceUtils.createNameTag(appName)); if (appVersion != null) { tags.add(ServiceUtils.createVersionTag(appVersion)); } if (appDescription != null) { tags.add(ServiceUtils.createDescriptionTag(appDescription)); } return tags; } /** * Validate the artifact. * @param artifact */ public abstract void validateArtifact(Artifact artifact, String compName, FileSystem fileSystem) throws IOException; protected abstract void validateConfigFile(ConfigFile configFile, String compName, FileSystem fileSystem) throws IOException; /** * Validate the config files. * @param configFiles config file list * @param fs file system */ public void validateConfigFiles(List configFiles, String compName, FileSystem fs) throws IOException { Set destFileSet = new HashSet<>(); for (ConfigFile file : configFiles) { if (file.getType() == null) { throw new IllegalArgumentException("File type is empty"); } ConfigFile.TypeEnum fileType = file.getType(); if (fileType.equals(ConfigFile.TypeEnum.TEMPLATE)) { if (StringUtils.isEmpty(file.getSrcFile()) && !file.getProperties().containsKey(CONTENT)) { throw new IllegalArgumentException(MessageFormat.format("For {0} " + "format, either src_file must be specified in ConfigFile," + " or the \"{1}\" key must be specified in " + "the 'properties' field of ConfigFile. ", ConfigFile.TypeEnum.TEMPLATE, CONTENT)); } } else if (fileType.equals(ConfigFile.TypeEnum.STATIC) || fileType.equals( ConfigFile.TypeEnum.ARCHIVE)) { if (!file.getProperties().isEmpty()) { throw new IllegalArgumentException(String .format("For %s format, should not specify any 'properties.'", fileType)); } String srcFile = file.getSrcFile(); if (srcFile == null || srcFile.isEmpty()) { throw new IllegalArgumentException(String.format( "For %s format, should make sure that srcFile is specified", fileType)); } FileStatus fileStatus = fs.getFileStatus(new Path(srcFile)); if (fileStatus != null && fileStatus.isDirectory()) { throw new IllegalArgumentException("srcFile=" + srcFile + " is a directory, which is not supported."); } } if (!StringUtils.isEmpty(file.getSrcFile())) { Path p = new Path(file.getSrcFile()); if (!fs.exists(p)) { throw new IllegalArgumentException( "Specified src_file does not exist on " + fs.getScheme() + ": " + file.getSrcFile()); } } if (StringUtils.isEmpty(file.getDestFile())) { throw new IllegalArgumentException("dest_file is empty."); } if (destFileSet.contains(file.getDestFile())) { throw new IllegalArgumentException( "Duplicated ConfigFile exists: " + file.getDestFile()); } destFileSet.add(file.getDestFile()); java.nio.file.Path destPath = Paths.get(file.getDestFile()); if (!destPath.isAbsolute() && destPath.getNameCount() > 1) { throw new IllegalArgumentException("Non-absolute dest_file has more " + "than one path element"); } // provider-specific validation validateConfigFile(file, compName, fs); } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 14658 https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/AbstractClientProvider.java/#L38-L150 1 2501 14658
1907 YES I found bad smells the bad smells are: 1. Long class 2. Long method (execute) 3. Data Class (SparkCubingMerge) 4. Inconsistent method names (e.g. getOptions vs execute) 5. Magic numbers/strings (e.g. "segment", "metaUrl") 6. Inconsistent formatting and spacing 7. Feature envy (multiple method calls to instance variables) 8. Dead code (initialized boolean in ReEncodeCuboidFunction) 9. Complex logic and nested functions (ReEncodeCuboidFunction) 10. Code duplication (multiple uses of OPTION_META_URL, OPTION_CUBE_NAME, etc.) I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } }
blob  Long class2 Long method (execute)3 Data Class (SparkCubingMerge)4 Inconsistent method names (eg getOptions vs execute)5 Magic numbers/strings (eg "segment", "metaUrl")6 Inconsistent formatting and spacing7 Feature envy (multiple method calls to instance variables)8 Dead code (initialized boolean in ReEncodeCuboidFunction)9 Complex logic and nested functions (ReEncodeCuboidFunction) t f f . Long class2. Long method (execute)3. Data Class (SparkCubingMerge)4. Inconsistent method names (e.g. getOptions vs execute)5. Magic numbers/strings (e.g. "segment", "metaUrl")6. Inconsistent formatting and spacing7. Feature envy (multiple method calls to instance variables)8. Dead code (initialized boolean in ReEncodeCuboidFunction)9. Complex logic and nested functions (ReEncodeCuboidFunction) blob 0 12386 https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 2 1907 12386
1565 { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11326 https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 1 1565 11326
4204    { "output": "YES I found bad smells\nthe bad smells are: 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } }
blob 2. data class t t f 2. data class blob 0 11063 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 1 4204 11063
1628      { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } }
blob Blob, Data Class t f t  Data Class   0 11502 https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 1 1628 11502
976 {"message":"YES I found bad smells","bad smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PhTypeUtil { public static byte[] toBytes(Object v, PhType phType) { if (v == null) return null; byte[] b = null; if (phType == PhType.DEFAULT) { PhType phType1 = PhType.getType(v.getClass()); if (phType1 != null && phType1 != PhType.DEFAULT) { toBytes(v, phType1); } } else if (phType == PhType.INTEGER) { b = new byte[Bytes.SIZEOF_INT]; encodeInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.UNSIGNED_INT) { b = new byte[Bytes.SIZEOF_INT]; encodeUnsignedInt(((Number) v).intValue(), b, 0); } else if (phType == PhType.BIGINT) { b = new byte[Bytes.SIZEOF_LONG]; encodeLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.UNSIGNED_LONG) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedLong(((Number) v).longValue(), b, 0); } else if (phType == PhType.SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { b = new byte[Bytes.SIZEOF_SHORT]; encodeUnsignedShort(((Number) v).shortValue(), b, 0); } else if (phType == PhType.TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { b = new byte[Bytes.SIZEOF_BYTE]; encodeUnsignedByte(((Number) v).byteValue(), b, 0); } else if (phType == PhType.FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { b = new byte[Bytes.SIZEOF_FLOAT]; encodeUnsignedFloat(((Number) v).floatValue(), b, 0); } else if (phType == PhType.DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { b = new byte[Bytes.SIZEOF_DOUBLE]; encodeUnsignedDouble(((Number) v).doubleValue(), b, 0); } else if (phType == PhType.BOOLEAN) { if ((Boolean) v) { b = new byte[] { 1 }; } else { b = new byte[] { 0 }; } } else if (phType == PhType.TIME || phType == PhType.DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeDate(v, b, 0); } else if (phType == PhType.TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeTimestamp(v, b, 0); } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { b = new byte[Bytes.SIZEOF_LONG]; encodeUnsignedDate(v, b, 0); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { b = new byte[Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT]; encodeUnsignedTimestamp(v, b, 0); } else if (phType == PhType.VARBINARY) { b = (byte[]) v; } else if (phType == PhType.VARCHAR) { b = Bytes.toBytes(v.toString()); } else if (phType == PhType.DECIMAL) { if (v instanceof BigDecimal) { b = encodeDecimal(v); } else if (v instanceof Number) { b = encodeDecimal(new BigDecimal(v.toString())); } } return b; } public static Object toObject(byte[] b, PhType phType) { if (b == null) return null; Object v = null; if (phType == PhType.INTEGER) { v = decodeInt(b, 0); } else if (phType == PhType.UNSIGNED_INT) { v = decodeUnsignedInt(b, 0); } else if (phType == PhType.BIGINT) { v = decodeLong(b, 0); } else if (phType == PhType.UNSIGNED_LONG) { v = decodeUnsignedLong(b, 0); } else if (phType == PhType.SMALLINT) { v = decodeShort(b, 0); } else if (phType == PhType.UNSIGNED_SMALLINT) { v = decodeUnsignedShort(b, 0); } else if (phType == PhType.TINYINT) { v = decodeByte(b, 0); } else if (phType == PhType.UNSIGNED_TINYINT) { v = decodeUnsignedByte(b, 0); } else if (phType == PhType.FLOAT) { v = decodeFloat(b, 0); } else if (phType == PhType.UNSIGNED_FLOAT) { v = decodeUnsignedFloat(b, 0); } else if (phType == PhType.DOUBLE) { v = decodeDouble(b, 0); } else if (phType == PhType.UNSIGNED_DOUBLE) { v = decodeUnsignedDouble(b, 0); } else if (phType == PhType.BOOLEAN) { checkForSufficientLength(b, 0, Bytes.SIZEOF_BOOLEAN); if (b[0] == 1) { v = true; } else if (b[0] == 0) { v = false; } } else if (phType == PhType.DATE) { v = new java.sql.Date(decodeLong(b, 0)); } else if (phType == PhType.TIME) { v = new java.sql.Time(decodeLong(b, 0)); } else if (phType == PhType.TIMESTAMP) { long millisDeserialized = decodeLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.UNSIGNED_TIME || phType == PhType.UNSIGNED_DATE) { v = new Date(decodeUnsignedLong(b, 0)); } else if (phType == PhType.UNSIGNED_TIMESTAMP) { long millisDeserialized = decodeUnsignedLong(b, 0); Timestamp ts = new Timestamp(millisDeserialized); int nanosDeserialized = decodeUnsignedInt(b, Bytes.SIZEOF_LONG); ts.setNanos(nanosDeserialized < 1000000 ? ts.getNanos() + nanosDeserialized : nanosDeserialized); v = ts; } else if (phType == PhType.VARBINARY) { v = b; } else if (phType == PhType.VARCHAR || phType == PhType.DEFAULT) { v = Bytes.toString(b); } else if (phType == PhType.DECIMAL) { v = decodeDecimal(b, 0, b.length); } return v; } private static int decodeInt(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_INT); int v; v = bytes[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_INT; i++) { v = (v << 8) + (bytes[o + i] & 0xff); } return v; } private static int encodeInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 16); b[o + 2] = (byte) (v >> 8); b[o + 3] = (byte) v; return Bytes.SIZEOF_INT; } private static int decodeUnsignedInt(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int v = Bytes.toInt(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedInt(int v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); if (v < 0) { throw new RuntimeException(); } Bytes.putInt(b, o, v); return Bytes.SIZEOF_INT; } private static long decodeLong(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long v; byte b = bytes[o]; v = b ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_LONG; i++) { b = bytes[o + i]; v = (v << 8) + (b & 0xff); } return v; } private static int encodeLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER // is binary comparable b[o + 1] = (byte) (v >> 48); b[o + 2] = (byte) (v >> 40); b[o + 3] = (byte) (v >> 32); b[o + 4] = (byte) (v >> 24); b[o + 5] = (byte) (v >> 16); b[o + 6] = (byte) (v >> 8); b[o + 7] = (byte) v; return Bytes.SIZEOF_LONG; } private static long decodeUnsignedLong(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long v = 0; for (int i = o; i < o + Bytes.SIZEOF_LONG; i++) { v <<= 8; v ^= b[i] & 0xFF; } if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedLong(long v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); if (v < 0) { throw new RuntimeException(); } Bytes.putLong(b, o, v); return Bytes.SIZEOF_LONG; } private static short decodeShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); int v; v = b[o] ^ 0x80; // Flip sign bit back for (int i = 1; i < Bytes.SIZEOF_SHORT; i++) { v = (v << 8) + (b[o + i] & 0xff); } return (short) v; } private static int encodeShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is // binary comparable b[o + 1] = (byte) v; return Bytes.SIZEOF_SHORT; } private static short decodeUnsignedShort(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); short v = Bytes.toShort(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedShort(short v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT); if (v < 0) { throw new RuntimeException(); } Bytes.putShort(b, o, v); return Bytes.SIZEOF_SHORT; } private static byte decodeByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); int v; v = b[o] ^ 0x80; // Flip sign bit back return (byte) v; } private static int encodeByte(byte v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary // comparable return Bytes.SIZEOF_BYTE; } private static byte decodeUnsignedByte(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE); byte v = b[o]; if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedByte(byte v, byte[] b, int o) { if (v < 0) { throw new RuntimeException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; } private static float decodeFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_INT); int value; value = Bytes.toInt(b, o); value--; value ^= (~value >> Integer.SIZE - 1) | Integer.MIN_VALUE; return Float.intBitsToFloat(value); } private static int encodeFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); int i = Float.floatToIntBits(v); i = (i ^ ((i >> Integer.SIZE - 1) | Integer.MIN_VALUE)) + 1; Bytes.putInt(b, o, i); return Bytes.SIZEOF_FLOAT; } private static float decodeUnsignedFloat(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); float v = Bytes.toFloat(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedFloat(float v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_FLOAT); if (v < 0) { throw new RuntimeException(); } Bytes.putFloat(b, o, v); return Bytes.SIZEOF_FLOAT; } private static double decodeDouble(byte[] bytes, int o) { checkForSufficientLength(bytes, o, Bytes.SIZEOF_LONG); long l; l = Bytes.toLong(bytes, o); l--; l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE; return Double.longBitsToDouble(l); } private static int encodeDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_LONG); long l = Double.doubleToLongBits(v); l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1; Bytes.putLong(b, o, l); return Bytes.SIZEOF_LONG; } private static double decodeUnsignedDouble(byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); double v = Bytes.toDouble(b, o); if (v < 0) { throw new RuntimeException(); } return v; } private static int encodeUnsignedDouble(double v, byte[] b, int o) { checkForSufficientLength(b, o, Bytes.SIZEOF_DOUBLE); if (v < 0) { throw new RuntimeException(); } Bytes.putDouble(b, o, v); return Bytes.SIZEOF_DOUBLE; } private static int encodeDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static int encodeUnsignedDate(Object v, byte[] b, int o) { if (v instanceof Date) { encodeUnsignedLong(((Date) v).getTime(), b, 0); } else if (v instanceof String) { String dateStr = (String) v; Date date; try { date = Util.parseDate(dateStr); if (date != null) { encodeUnsignedLong(date.getTime(), b, 0); } } catch (Exception e) { throw new RuntimeException(e); } } return Bytes.SIZEOF_LONG; } private static int encodeUnsignedTimestamp(Object v, byte[] b, int o) { if (v instanceof Timestamp) { Timestamp ts = (Timestamp) v; encodeUnsignedLong(ts.getTime(), b, o); Bytes.putInt(b, Bytes.SIZEOF_LONG, ts.getNanos() % 1000000); } else { encodeUnsignedDate(v, b, o); } return Bytes.SIZEOF_LONG + Bytes.SIZEOF_INT; } private static byte[] encodeDecimal(Object object) { if (object == null) { return new byte[0]; } BigDecimal v = (BigDecimal) object; v = v.round(DEFAULT_MATH_CONTEXT).stripTrailingZeros(); int len = getLength(v); byte[] result = new byte[Math.min(len, 21)]; decimalToBytes(v, result, 0, len); return result; } private static BigDecimal decodeDecimal(byte[] bytes, int offset, int length) { if (length == 1 && bytes[offset] == ZERO_BYTE) { return BigDecimal.ZERO; } int signum = ((bytes[offset] & 0x80) == 0) ? -1 : 1; int scale; int index; int digitOffset; long multiplier = 100L; int begIndex = offset + 1; if (signum == 1) { scale = (byte) (((bytes[offset] & 0x7F) - 65) * -2); index = offset + length; digitOffset = POS_DIGIT_OFFSET; } else { scale = (byte) ((~bytes[offset] - 65 - 128) * -2); index = offset + length - (bytes[offset + length - 1] == NEG_TERMINAL_BYTE ? 1 : 0); digitOffset = -NEG_DIGIT_OFFSET; } length = index - offset; long l = signum * bytes[--index] - digitOffset; if (l % 10 == 0) { // trailing zero scale--; // drop trailing zero and compensate in the scale l /= 10; multiplier = 10; } // Use long arithmetic for as long as we can while (index > begIndex) { if (l >= MAX_LONG_FOR_DESERIALIZE || multiplier >= Long.MAX_VALUE / 100) { multiplier = LongMath.divide(multiplier, 100L, RoundingMode.UNNECESSARY); break; // Exit loop early so we don't overflow our multiplier } int digit100 = signum * bytes[--index] - digitOffset; l += digit100 * multiplier; multiplier = LongMath.checkedMultiply(multiplier, 100); } BigInteger bi; // If still more digits, switch to BigInteger arithmetic if (index > begIndex) { bi = BigInteger.valueOf(l); BigInteger biMultiplier = BigInteger.valueOf(multiplier).multiply(ONE_HUNDRED); do { int digit100 = signum * bytes[--index] - digitOffset; bi = bi.add(biMultiplier.multiply(BigInteger.valueOf(digit100))); biMultiplier = biMultiplier.multiply(ONE_HUNDRED); } while (index > begIndex); if (signum == -1) { bi = bi.negate(); } } else { bi = BigInteger.valueOf(l * signum); } // Update the scale based on the precision scale += (length - 2) * 2; BigDecimal v = new BigDecimal(bi, scale); return v; } private static int getLength(BigDecimal v) { int signum = v.signum(); if (signum == 0) { // Special case for zero return 1; } return (signum < 0 ? 2 : 1) + (v.precision() + 1 + (v.scale() % 2 == 0 ? 0 : 1)) / 2; } private static final int MAX_PRECISION = 38; private static final MathContext DEFAULT_MATH_CONTEXT = new MathContext(MAX_PRECISION, RoundingMode.HALF_UP); private static final Integer MAX_BIG_DECIMAL_BYTES = 21; private static final byte ZERO_BYTE = (byte) 0x80; private static final byte NEG_TERMINAL_BYTE = (byte) 102; private static final int EXP_BYTE_OFFSET = 65; private static final int POS_DIGIT_OFFSET = 1; private static final int NEG_DIGIT_OFFSET = 101; private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); private static final long MAX_LONG_FOR_DESERIALIZE = Long.MAX_VALUE / 1000; private static int decimalToBytes(BigDecimal v, byte[] result, final int offset, int length) { int signum = v.signum(); if (signum == 0) { result[offset] = ZERO_BYTE; return 1; } int index = offset + length; int scale = v.scale(); int expOffset = scale % 2 * (scale < 0 ? -1 : 1); int multiplyBy; BigInteger divideBy; if (expOffset == 0) { multiplyBy = 1; divideBy = ONE_HUNDRED; } else { multiplyBy = 10; divideBy = BigInteger.TEN; } // Normalize the scale based on what is necessary to end up with a base // 100 // decimal (i.e. 10.123e3) int digitOffset; BigInteger compareAgainst; if (signum == 1) { digitOffset = POS_DIGIT_OFFSET; compareAgainst = MAX_LONG; scale -= (length - 2) * 2; result[offset] = (byte) ((-(scale + expOffset) / 2 + EXP_BYTE_OFFSET) | 0x80); } else { digitOffset = NEG_DIGIT_OFFSET; compareAgainst = MIN_LONG; // Scale adjustment shouldn't include terminal byte in length scale -= (length - 2 - 1) * 2; result[offset] = (byte) (~(-(scale + expOffset) / 2 + EXP_BYTE_OFFSET + 128) & 0x7F); if (length <= MAX_BIG_DECIMAL_BYTES) { result[--index] = NEG_TERMINAL_BYTE; } else { // Adjust length and offset down because we don't have enough // room length = MAX_BIG_DECIMAL_BYTES; index = offset + length; } } BigInteger bi = v.unscaledValue(); // Use BigDecimal arithmetic until we can fit into a long while (bi.compareTo(compareAgainst) * signum > 0) { BigInteger[] dandr = bi.divideAndRemainder(divideBy); bi = dandr[0]; int digit = dandr[1].intValue(); result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; divideBy = ONE_HUNDRED; } long l = bi.longValue(); do { long divBy = 100 / multiplyBy; long digit = l % divBy; l /= divBy; result[--index] = (byte) (digit * multiplyBy + digitOffset); multiplyBy = 1; } while (l != 0); return length; } private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) { if (b.length < offset + requiredLength) { throw new RuntimeException( "Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset)); } } }
blob long method, data class t t f long method, data class blob 0 8781 https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/support/PhTypeUtil.java/#L21-L609 1 976 8781
4044      { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; }
long method long method, data class t t t  data class   0 10690 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 1 4044 10690
2217          {"message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } }
long method long method, data class t t t  data class   0 13539 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 1 2217 13539
1876  { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } }
blob data class, long method t t f data class, long method blob 0 12264 https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 1 1876 12264
1152     { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; }
long method 1. long method, 2. data class t t t  2. data class   0 10133 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 1 1152 10133
588 {"answer": "YES I found bad smells", "the bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ImmutableBitSet implements Iterable, Serializable, Comparable { /** Compares bit sets topologically, so that enclosing bit sets come first, * using natural ordering to break ties. */ public static final Comparator COMPARATOR = (o1, o2) -> { if (o1.equals(o2)) { return 0; } if (o1.contains(o2)) { return -1; } if (o2.contains(o1)) { return 1; } return o1.compareTo(o2); }; public static final Ordering ORDERING = Ordering.from(COMPARATOR); // BitSets are packed into arrays of "words." Currently a word is // a long, which consists of 64 bits, requiring 6 address bits. // The choice of word size is determined purely by performance concerns. private static final int ADDRESS_BITS_PER_WORD = 6; private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; /* Used to shift left or right for a partial word mask */ private static final long WORD_MASK = 0xffffffffffffffffL; private static final long[] EMPTY_LONGS = new long[0]; private static final ImmutableBitSet EMPTY = new ImmutableBitSet(EMPTY_LONGS); @SuppressWarnings("Guava") @Deprecated // to be removed before 2.0 public static final com.google.common.base.Function FROM_BIT_SET = ImmutableBitSet::fromBitSet; private final long[] words; /** Private constructor. Does not copy the array. */ private ImmutableBitSet(long[] words) { this.words = words; assert words.length == 0 ? words == EMPTY_LONGS : words[words.length - 1] != 0L; } /** Creates an ImmutableBitSet with no bits. */ public static ImmutableBitSet of() { return EMPTY; } public static ImmutableBitSet of(int... bits) { int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } public static ImmutableBitSet of(Iterable bits) { if (bits instanceof ImmutableBitSet) { return (ImmutableBitSet) bits; } int max = -1; for (int bit : bits) { max = Math.max(bit, max); } if (max == -1) { return EMPTY; } long[] words = new long[wordIndex(max) + 1]; for (int bit : bits) { int wordIndex = wordIndex(bit); words[wordIndex] |= 1L << bit; } return new ImmutableBitSet(words); } /** * Creates an ImmutableBitSet with given bits set. * * For example, of(ImmutableIntList.of(0, 3)) returns a bit * set with bits {0, 3} set. * * @param bits Collection of bits to set * @return Bit set */ public static ImmutableBitSet of(ImmutableIntList bits) { return builder().addAll(bits).build(); } /** * Returns a new immutable bit set containing all the bits in the given long * array. * * More precisely, * * {@code ImmutableBitSet.valueOf(longs).get(n) * == ((longs[n/64] & (1L<<(n%64))) != 0)} * * for all {@code n < 64 * longs.length}. * * This method is equivalent to * {@code ImmutableBitSet.valueOf(LongBuffer.wrap(longs))}. * * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set * @return a {@code ImmutableBitSet} containing all the bits in the long * array */ public static ImmutableBitSet valueOf(long... longs) { int n = longs.length; while (n > 0 && longs[n - 1] == 0) { --n; } if (n == 0) { return EMPTY; } return new ImmutableBitSet(Arrays.copyOf(longs, n)); } /** * Returns a new immutable bit set containing all the bits in the given long * buffer. */ public static ImmutableBitSet valueOf(LongBuffer longs) { longs = longs.slice(); int n = longs.remaining(); while (n > 0 && longs.get(n - 1) == 0) { --n; } if (n == 0) { return EMPTY; } long[] words = new long[n]; longs.get(words); return new ImmutableBitSet(words); } /** * Returns a new immutable bit set containing all the bits in the given * {@link BitSet}. */ public static ImmutableBitSet fromBitSet(BitSet input) { return ImmutableBitSet.of(BitSets.toIter(input)); } /** * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * For example, {@code range(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static ImmutableBitSet range(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex == toIndex) { return EMPTY; } int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); long[] words = new long[endWordIndex + 1]; long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } return new ImmutableBitSet(words); } /** Creates an ImmutableBitSet with bits between 0 and {@code toIndex} set. */ public static ImmutableBitSet range(int toIndex) { return range(0, toIndex); } /** * Given a bit index, return word index containing it. */ private static int wordIndex(int bitIndex) { return bitIndex >> ADDRESS_BITS_PER_WORD; } /** Computes the power set (set of all sets) of this bit set. */ public Iterable powerSet() { List> singletons = new ArrayList<>(); for (int bit : this) { singletons.add( ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit))); } return Iterables.transform(Linq4j.product(singletons), ImmutableBitSet::union); } /** * Returns the value of the bit with the specified index. The value * is {@code true} if the bit with the index {@code bitIndex} * is currently set in this {@code ImmutableBitSet}; otherwise, the result * is {@code false}. * * @param bitIndex the bit index * @return the value of the bit with the specified index * @throws IndexOutOfBoundsException if the specified index is negative */ public boolean get(int bitIndex) { if (bitIndex < 0) { throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex); } int wordIndex = wordIndex(bitIndex); return (wordIndex < words.length) && ((words[wordIndex] & (1L << bitIndex)) != 0); } /** * Returns a new {@code ImmutableBitSet} * composed of bits from this {@code ImmutableBitSet} * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include * @param toIndex index after the last bit to include * @return a new {@code ImmutableBitSet} from a range of * this {@code ImmutableBitSet} * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, * or {@code toIndex} is negative, or {@code fromIndex} is * larger than {@code toIndex} */ public ImmutableBitSet get(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); final Builder builder = builder(); for (int i = nextSetBit(fromIndex); i >= 0 && i < toIndex; i = nextSetBit(i + 1)) { builder.set(i); } return builder.build(); } /** * Checks that fromIndex ... toIndex is a valid range of bit indices. */ private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } if (toIndex < 0) { throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); } if (fromIndex > toIndex) { throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex); } } /** * Returns a string representation of this bit set. For every index * for which this {@code BitSet} contains a bit in the set * state, the decimal representation of that index is included in * the result. Such indices are listed in order from lowest to * highest, separated by ", " (a comma and a space) and * surrounded by braces, resulting in the usual mathematical * notation for a set of integers. * * Example: * * BitSet drPepper = new BitSet(); * Now {@code drPepper.toString()} returns "{@code {}}". * * drPepper.set(2); * Now {@code drPepper.toString()} returns "{@code {2}}". * * drPepper.set(4); * drPepper.set(10); * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". * * @return a string representation of this bit set */ public String toString() { int numBits = words.length * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); } /** * Returns true if the specified {@code ImmutableBitSet} has any bits set to * {@code true} that are also set to {@code true} in this * {@code ImmutableBitSet}. * * @param set {@code ImmutableBitSet} to intersect with * @return boolean indicating whether this {@code ImmutableBitSet} intersects * the specified {@code ImmutableBitSet} */ public boolean intersects(ImmutableBitSet set) { for (int i = Math.min(words.length, set.words.length) - 1; i >= 0; i--) { if ((words[i] & set.words[i]) != 0) { return true; } } return false; } /** Returns the number of bits set to {@code true} in this * {@code ImmutableBitSet}. * * @see #size() */ public int cardinality() { return countBits(words); } private static int countBits(long[] words) { int sum = 0; for (long word : words) { sum += Long.bitCount(word); } return sum; } /** * Returns the hash code value for this bit set. The hash code * depends only on which bits are set within this {@code ImmutableBitSet}. * * The hash code is defined using the same calculation as * {@link java.util.BitSet#hashCode()}. * * @return the hash code value for this bit set */ public int hashCode() { long h = 1234; for (int i = words.length; --i >= 0;) { h ^= words[i] * (i + 1); } return (int) ((h >> 32) ^ h); } /** * Returns the number of bits of space actually in use by this * {@code ImmutableBitSet} to represent bit values. * The maximum element in the set is the size - 1st element. * * @return the number of bits currently in this bit set * * @see #cardinality() */ public int size() { return words.length * BITS_PER_WORD; } /** * Compares this object against the specified object. * The result is {@code true} if and only if the argument is * not {@code null} and is a {@code ImmutableBitSet} object that has * exactly the same set of bits set to {@code true} as this bit * set. * * @param obj the object to compare with * @return {@code true} if the objects are the same; * {@code false} otherwise * @see #size() */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ImmutableBitSet)) { return false; } ImmutableBitSet set = (ImmutableBitSet) obj; return Arrays.equals(words, set.words); } /** Compares this ImmutableBitSet with another, using a lexicographic * ordering. * * Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted * order. */ public int compareTo(@Nonnull ImmutableBitSet o) { int i = 0; for (;;) { int n0 = nextSetBit(i); int n1 = o.nextSetBit(i); int c = Utilities.compare(n0, n1); if (c != 0 || n0 < 0) { return c; } i = n0 + 1; } } /** * Returns the index of the first bit that is set to {@code true} * that occurs on or after the specified starting index. If no such * bit exists then {@code -1} is returned. * * Based upon {@link BitSet#nextSetBit}. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next set bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return -1; } long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return -1; } word = words[u]; } } /** * Returns the index of the first bit that is set to {@code false} * that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the next clear bit * @throws IndexOutOfBoundsException if the specified index is negative */ public int nextClearBit(int fromIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) { return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); } if (++u == words.length) { return words.length * BITS_PER_WORD; } word = ~words[u]; } } /** * Returns the index of the nearest bit that is set to {@code false} * that occurs on or before the specified starting index. * If no such bit exists, or if {@code -1} is given as the * starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous clear bit, or {@code -1} if there * is no such bit * @throws IndexOutOfBoundsException if the specified index is less * than {@code -1} */ public int previousClearBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) { return -1; } throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex); } int u = wordIndex(fromIndex); if (u >= words.length) { return fromIndex; } long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1)); while (true) { if (word != 0) { return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word); } if (u-- == 0) { return -1; } word = ~words[u]; } } public Iterator iterator() { return new Iterator() { int i = nextSetBit(0); public boolean hasNext() { return i >= 0; } public Integer next() { int prev = i; i = nextSetBit(i + 1); return prev; } public void remove() { throw new UnsupportedOperationException(); } }; } /** Converts this bit set to a list. */ public List toList() { final List list = new ArrayList<>(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { list.add(i); } return list; } /** Creates a view onto this bit set as a list of integers. * * The {@code cardinality} and {@code get} methods are both O(n), but * the iterator is efficient. The list is memory efficient, and the CPU cost * breaks even (versus {@link #toList}) if you intend to scan it only once. */ public List asList() { return new AbstractList() { @Override public Integer get(int index) { return nth(index); } @Override public int size() { return cardinality(); } @Nonnull @Override public Iterator iterator() { return ImmutableBitSet.this.iterator(); } }; } /** Creates a view onto this bit set as a set of integers. * * The {@code size} and {@code contains} methods are both O(n), but the * iterator is efficient. */ public Set asSet() { return new AbstractSet() { @Nonnull public Iterator iterator() { return ImmutableBitSet.this.iterator(); } public int size() { return cardinality(); } @Override public boolean contains(Object o) { return ImmutableBitSet.this.get((Integer) o); } }; } /** * Converts this bit set to an array. * * Each entry of the array is the ordinal of a set bit. The array is * sorted. * * @return Array of set bits */ public int[] toArray() { final int[] integers = new int[cardinality()]; int j = 0; for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { integers[j++] = i; } return integers; } /** * Converts this bit set to an array of little-endian words. */ public long[] toLongArray() { return words.length == 0 ? words : words.clone(); } /** Returns the union of this immutable bit set with a {@link BitSet}. */ public ImmutableBitSet union(BitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(BitSets.toIter(other)) .build(); } /** Returns the union of this bit set with another. */ public ImmutableBitSet union(ImmutableBitSet other) { return rebuild() // remember "this" and try to re-use later .addAll(other) .build(other); // try to re-use "other" } /** Returns the union of a number of bit sets. */ public static ImmutableBitSet union( Iterable sets) { final Builder builder = builder(); for (ImmutableBitSet set : sets) { builder.addAll(set); } return builder.build(); } /** Returns a bit set with all the bits in this set that are not in * another. * * @see BitSet#andNot(java.util.BitSet) */ public ImmutableBitSet except(ImmutableBitSet that) { final Builder builder = rebuild(); builder.removeAll(that); return builder.build(); } /** Returns a bit set with all the bits set in both this set and in * another. * * @see BitSet#and */ public ImmutableBitSet intersect(ImmutableBitSet that) { final Builder builder = rebuild(); builder.intersect(that); return builder.build(); } /** * Returns true if all bits set in the second parameter are also set in the * first. In other words, whether x is a super-set of y. * * @param set1 Bitmap to be checked * * @return Whether all bits in set1 are set in set0 */ public boolean contains(ImmutableBitSet set1) { for (int i = set1.nextSetBit(0); i >= 0; i = set1.nextSetBit(i + 1)) { if (!get(i)) { return false; } } return true; } /** * The ordinal of a given bit, or -1 if it is not set. */ public int indexOf(int bit) { for (int i = nextSetBit(0), k = 0;; i = nextSetBit(i + 1), ++k) { if (i < 0) { return -1; } if (i == bit) { return k; } } } /** Computes the closure of a map from integers to bits. * * The input must have an entry for each position. * * Does not modify the input map or its bit sets. */ public static SortedMap closure( SortedMap equivalence) { if (equivalence.isEmpty()) { return ImmutableSortedMap.of(); } int length = equivalence.lastKey(); for (ImmutableBitSet bitSet : equivalence.values()) { length = Math.max(length, bitSet.length()); } if (equivalence.size() < length || equivalence.firstKey() != 0) { SortedMap old = equivalence; equivalence = new TreeMap<>(); for (int i = 0; i < length; i++) { final ImmutableBitSet bitSet = old.get(i); equivalence.put(i, bitSet == null ? ImmutableBitSet.of() : bitSet); } } final Closure closure = new Closure(equivalence); return closure.closure; } /** * Returns the "logical size" of this {@code ImmutableBitSet}: the index of * the highest set bit in the {@code ImmutableBitSet} plus one. Returns zero * if the {@code ImmutableBitSet} contains no set bits. * * @return the logical size of this {@code ImmutableBitSet} */ public int length() { if (words.length == 0) { return 0; } return BITS_PER_WORD * (words.length - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[words.length - 1])); } /** * Returns true if this {@code ImmutableBitSet} contains no bits that are set * to {@code true}. */ public boolean isEmpty() { return words.length == 0; } /** Creates an empty Builder. */ public static Builder builder() { return new Builder(EMPTY_LONGS); } @Deprecated // to be removed before 2.0 public static Builder builder(ImmutableBitSet bitSet) { return bitSet.rebuild(); } /** Creates a Builder whose initial contents are the same as this * ImmutableBitSet. */ public Builder rebuild() { return new Rebuilder(this); } /** Returns the {@code n}th set bit. * * @throws java.lang.IndexOutOfBoundsException if n is less than 0 or greater * than the number of bits set */ public int nth(int n) { int start = 0; for (long word : words) { final int bitCount = Long.bitCount(word); if (n < bitCount) { while (word != 0) { if ((word & 1) == 1) { if (n == 0) { return start; } --n; } word >>= 1; ++start; } } start += 64; n -= bitCount; } throw new IndexOutOfBoundsException("index out of range: " + n); } /** Returns a bit set the same as this but with a given bit set. */ public ImmutableBitSet set(int i) { return union(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit set (if b is * true) or unset (if b is false). */ public ImmutableBitSet set(int i, boolean b) { if (get(i) == b) { return this; } return b ? set(i) : clear(i); } /** Returns a bit set the same as this but with a given bit set if condition * is true. */ public ImmutableBitSet setIf(int bit, boolean condition) { return condition ? set(bit) : this; } /** Returns a bit set the same as this but with a given bit cleared. */ public ImmutableBitSet clear(int i) { return except(ImmutableBitSet.of(i)); } /** Returns a bit set the same as this but with a given bit cleared if * condition is true. */ public ImmutableBitSet clearIf(int i, boolean condition) { return condition ? except(ImmutableBitSet.of(i)) : this; } /** Returns a {@link BitSet} that has the same contents as this * {@code ImmutableBitSet}. */ public BitSet toBitSet() { return BitSets.of(this); } /** Permutes a bit set according to a given mapping. */ public ImmutableBitSet permute(Map map) { final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(map.get(i)); } return builder.build(); } /** Permutes a collection of bit sets according to a given mapping. */ public static Iterable permute( Iterable bitSets, final Map map) { return Iterables.transform(bitSets, bitSet -> bitSet.permute(map)); } /** Returns a bit set with every bit moved up {@code offset} positions. * Offset may be negative, but throws if any bit ends up negative. */ public ImmutableBitSet shift(int offset) { if (offset == 0) { return this; } final Builder builder = builder(); for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) { builder.set(i + offset); } return builder.build(); } /** * Setup equivalence Sets for each position. If i and j are equivalent then * they will have the same equivalence Set. The algorithm computes the * closure relation at each position for the position wrt to positions * greater than it. Once a closure is computed for a position, the closure * Set is set on all its descendants. So the closure computation bubbles up * from lower positions and the final equivalence Set is propagated down * from the lowest element in the Set. */ private static class Closure { private SortedMap equivalence; private final SortedMap closure = new TreeMap<>(); Closure(SortedMap equivalence) { this.equivalence = equivalence; final ImmutableIntList keys = ImmutableIntList.copyOf(equivalence.keySet()); for (int pos : keys) { computeClosure(pos); } } private ImmutableBitSet computeClosure(int pos) { ImmutableBitSet o = closure.get(pos); if (o != null) { return o; } final ImmutableBitSet b = equivalence.get(pos); o = b; int i = b.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { o = o.union(computeClosure(i)); } closure.put(pos, o); i = o.nextSetBit(pos + 1); for (; i >= 0; i = b.nextSetBit(i + 1)) { closure.put(i, o); } return o; } } /** Builder. */ public static class Builder { private long[] words; private Builder(long[] words) { this.words = words; } /** Builds an ImmutableBitSet from the contents of this Builder. * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build() { if (words.length == 0) { return EMPTY; } long[] words = this.words; this.words = null; // prevent re-use of builder return new ImmutableBitSet(words); } /** Builds an ImmutableBitSet from the contents of this Builder, using * an existing ImmutableBitSet if it happens to have the same contents. * * Supplying the existing bit set if useful for set operations, * where there is a significant chance that the original bit set is * unchanged. We save memory because we use the same copy. For example: * * * ImmutableBitSet primeNumbers; * ImmutableBitSet hundreds = ImmutableBitSet.of(100, 200, 300); * return primeNumbers.except(hundreds); * * After calling this method, the Builder cannot be used again. */ public ImmutableBitSet build(ImmutableBitSet bitSet) { if (wouldEqual(bitSet)) { return bitSet; } return build(); } public Builder set(int bit) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } int wordIndex = wordIndex(bit); if (wordIndex >= words.length) { words = Arrays.copyOf(words, wordIndex + 1); } words[wordIndex] |= 1L << bit; return this; } private void trim(int wordCount) { while (wordCount > 0 && words[wordCount - 1] == 0L) { --wordCount; } if (wordCount == words.length) { return; } if (wordCount == 0) { words = EMPTY_LONGS; } else { words = Arrays.copyOfRange(words, 0, wordCount); } } public Builder clear(int bit) { int wordIndex = wordIndex(bit); if (wordIndex < words.length) { words[wordIndex] &= ~(1L << bit); trim(words.length); } return this; } /** Returns whether the bit set that would be created by this Builder would * equal a given bit set. */ public boolean wouldEqual(ImmutableBitSet bitSet) { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return Arrays.equals(words, bitSet.words); } /** Returns the number of set bits. */ public int cardinality() { if (words == null) { throw new IllegalArgumentException("can only use builder once"); } return countBits(words); } /** Sets all bits in a given bit set. */ public Builder addAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { set(bit); } return this; } /** Sets all bits in a given list of bits. */ public Builder addAll(Iterable integers) { for (Integer integer : integers) { set(integer); } return this; } /** Sets all bits in a given list of {@code int}s. */ public Builder addAll(ImmutableIntList integers) { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < integers.size(); i++) { set(integers.get(i)); } return this; } /** Clears all bits in a given bit set. */ public Builder removeAll(ImmutableBitSet bitSet) { for (Integer bit : bitSet) { clear(bit); } return this; } /** Sets a range of bits, from {@code from} to {@code to} - 1. */ public Builder set(int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException(); } if (toIndex < 0) { throw new IllegalArgumentException(); } if (fromIndex < toIndex) { // Increase capacity if necessary int startWordIndex = wordIndex(fromIndex); int endWordIndex = wordIndex(toIndex - 1); if (endWordIndex >= words.length) { words = Arrays.copyOf(words, endWordIndex + 1); } long firstWordMask = WORD_MASK << fromIndex; long lastWordMask = WORD_MASK >>> -toIndex; if (startWordIndex == endWordIndex) { // One word words[startWordIndex] |= firstWordMask & lastWordMask; } else { // First word, middle words, last word words[startWordIndex] |= firstWordMask; for (int i = startWordIndex + 1; i < endWordIndex; i++) { words[i] = WORD_MASK; } words[endWordIndex] |= lastWordMask; } } return this; } public boolean isEmpty() { return words.length == 0; } public void intersect(ImmutableBitSet that) { int x = Math.min(words.length, that.words.length); for (int i = 0; i < x; i++) { words[i] &= that.words[i]; } trim(x); } } /** Refinement of {@link Builder} that remembers its original * {@link org.apache.calcite.util.ImmutableBitSet} and tries to use it * when {@link #build} is called. */ private static class Rebuilder extends Builder { private final ImmutableBitSet originalBitSet; private Rebuilder(ImmutableBitSet originalBitSet) { super(originalBitSet.words.clone()); this.originalBitSet = originalBitSet; } @Override public ImmutableBitSet build() { if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(); } @Override public ImmutableBitSet build(ImmutableBitSet bitSet) { // We try to re-use both originalBitSet and bitSet. if (wouldEqual(originalBitSet)) { return originalBitSet; } return super.build(bitSet); } } }
blob data class, long method t t f data class, long method blob 0 5858 https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java/#L46-L1144 1 588 5858
1599       { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } }
blob long method, data class t t f long method, data class blob 0 11418 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 1 1599 11418
1147      { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); }
long method long method, data class t t t  data class   0 10122 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 1 1147 10122
1025      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } }
feature envy long method, data class t t f long method, data class feature envy 0 9360 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 1 1025 9360
4370 {"response":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } }
blob data class, long method t t f data class, long method blob 0 11535 https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 1 4370 11535
5146 { "YES I found bad smells": true, "the bad smells are": [ "2. Data Class", "4. Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } }
blob 2. data class, 4. long method t t f 2. data class, 4. long method blob 0 14395 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 1 5146 14395
1153 { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Annotate { protected static final Context.Key annotateKey = new Context.Key<>(); public static Annotate instance(Context context) { Annotate instance = context.get(annotateKey); if (instance == null) instance = new Annotate(context); return instance; } private final Attr attr; private final Check chk; private final ConstFold cfolder; private final DeferredLintHandler deferredLintHandler; private final Enter enter; private final Lint lint; private final Log log; private final Names names; private final Resolve resolve; private final TreeMaker make; private final Symtab syms; private final TypeEnvs typeEnvs; private final Types types; private final Attribute theUnfinishedDefaultValue; private final boolean allowRepeatedAnnos; private final String sourceName; protected Annotate(Context context) { context.put(annotateKey, this); attr = Attr.instance(context); chk = Check.instance(context); cfolder = ConstFold.instance(context); deferredLintHandler = DeferredLintHandler.instance(context); enter = Enter.instance(context); log = Log.instance(context); lint = Lint.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); resolve = Resolve.instance(context); syms = Symtab.instance(context); typeEnvs = TypeEnvs.instance(context); types = Types.instance(context); theUnfinishedDefaultValue = new Attribute.Error(syms.errType); Source source = Source.instance(context); allowRepeatedAnnos = Feature.REPEATED_ANNOTATIONS.allowedInSource(source); sourceName = source.name; blockCount = 1; } /** Semaphore to delay annotation processing */ private int blockCount = 0; /** Called when annotations processing needs to be postponed. */ public void blockAnnotations() { blockCount++; } /** Called when annotation processing can be resumed. */ public void unblockAnnotations() { blockCount--; if (blockCount == 0) flush(); } /** Variant which allows for a delayed flush of annotations. * Needed by ClassReader */ public void unblockAnnotationsNoFlush() { blockCount--; } /** are we blocking annotation processing? */ public boolean annotationsBlocked() {return blockCount > 0; } public void enterDone() { unblockAnnotations(); } public List fromAnnotations(List annotations) { if (annotations.isEmpty()) { return List.nil(); } ListBuffer buf = new ListBuffer<>(); for (JCAnnotation anno : annotations) { Assert.checkNonNull(anno.attribute); buf.append((TypeCompound) anno.attribute); } return buf.toList(); } /** Annotate (used for everything else) */ public void normal(Runnable r) { q.append(r); } /** Validate, triggers after 'normal' */ public void validate(Runnable a) { validateQ.append(a); } /** Flush all annotation queues */ public void flush() { if (annotationsBlocked()) return; if (isFlushing()) return; startFlushing(); try { while (q.nonEmpty()) { q.next().run(); } while (typesQ.nonEmpty()) { typesQ.next().run(); } while (afterTypesQ.nonEmpty()) { afterTypesQ.next().run(); } while (validateQ.nonEmpty()) { validateQ.next().run(); } } finally { doneFlushing(); } } private ListBuffer q = new ListBuffer<>(); private ListBuffer validateQ = new ListBuffer<>(); private int flushCount = 0; private boolean isFlushing() { return flushCount > 0; } private void startFlushing() { flushCount++; } private void doneFlushing() { flushCount--; } ListBuffer typesQ = new ListBuffer<>(); ListBuffer afterTypesQ = new ListBuffer<>(); public void typeAnnotation(Runnable a) { typesQ.append(a); } public void afterTypes(Runnable a) { afterTypesQ.append(a); } /** * Queue annotations for later attribution and entering. This is probably the method you are looking for. * * @param annotations the list of JCAnnotations to attribute and enter * @param localEnv the enclosing env * @param s ths Symbol on which to enter the annotations * @param deferPos report errors here */ public void annotateLater(List annotations, Env localEnv, Symbol s, DiagnosticPosition deferPos) { if (annotations.isEmpty()) { return; } s.resetAnnotations(); // mark Annotations as incomplete for now normal(() -> { // Packages are unusual, in that they are the only type of declaration that can legally appear // more than once in a compilation, and in all cases refer to the same underlying symbol. // This means they are the only kind of declaration that syntactically may have multiple sets // of annotations, each on a different package declaration, even though that is ultimately // forbidden by JLS 8 section 7.4. // The corollary here is that all of the annotations on a package symbol may have already // been handled, meaning that the set of annotations pending completion is now empty. Assert.check(s.kind == PCK || s.annotationsPendingCompletion()); JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferPos != null ? deferredLintHandler.setPos(deferPos) : deferredLintHandler.immediate(); Lint prevLint = deferPos != null ? null : chk.setLint(lint); try { if (s.hasAnnotations() && annotations.nonEmpty()) log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s)); Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null"); // false is passed as fifth parameter since annotateLater is // never called for a type parameter annotateNow(s, annotations, localEnv, false, false); } finally { if (prevLint != null) chk.setLint(prevLint); deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { chk.validateAnnotations(annotations, s); } finally { log.useSource(prev); } }); } /** Queue processing of an attribute default value. */ public void annotateDefaultValueLater(JCExpression defaultValue, Env localEnv, MethodSymbol m, DiagnosticPosition deferPos) { normal(() -> { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } }); validate(() -> { //validate annotations JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // if default value is an annotation, check it is a well-formed // annotation value (e.g. no duplicate values, no missing values, etc.) chk.validateAnnotationTree(defaultValue); } finally { log.useSource(prev); } }); } /** Enter a default value for an annotation element. */ private void enterDefaultValue(JCExpression defaultValue, Env localEnv, MethodSymbol m) { m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv); } /** * Gather up annotations into a map from type symbols to lists of Compound attributes, * then continue on with repeating annotations processing. */ private void annotateNow(Symbol toAnnotate, List withAnnotations, Env env, boolean typeAnnotations, boolean isTypeParam) { Map> annotated = new LinkedHashMap<>(); Map pos = new HashMap<>(); for (List al = withAnnotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; T c; if (typeAnnotations) { @SuppressWarnings("unchecked") T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env); c = tmp; } else { @SuppressWarnings("unchecked") T tmp = (T)attributeAnnotation(a, syms.annotationType, env); c = tmp; } Assert.checkNonNull(c, "Failed to create annotation"); if (a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); } ListBuffer l = annotated.get(a.type.tsym); l = l.append(c); annotated.put(a.type.tsym, l); pos.put(c, a.pos()); } else { annotated.put(a.type.tsym, ListBuffer.of(c)); pos.put(c, a.pos()); } } // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH) && types.isSameType(c.type, syms.deprecatedType)) { toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); Attribute fr = c.member(names.forRemoval); if (fr instanceof Attribute.Constant) { Attribute.Constant v = (Attribute.Constant) fr; if (v.type == syms.booleanType && ((Integer) v.value) != 0) { toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL; } } } } List buf = List.nil(); for (ListBuffer lb : annotated.values()) { if (lb.size() == 1) { buf = buf.prepend(lb.first()); } else { AnnotationContext ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations); T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam); if (res != null) buf = buf.prepend(res); } } if (typeAnnotations) { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.appendUniqueTypeAttributes(attrs); } else { @SuppressWarnings("unchecked") List attrs = (List)buf.reverse(); toAnnotate.resetAnnotations(); toAnnotate.setDeclarationAttributes(attrs); } } /** * Attribute and store a semantic representation of the annotation tree {@code tree} into the * tree.attribute field. * * @param tree the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the current env in where the annotation instance is found */ public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (tree.attribute != null && tree.type != null) return tree.attribute; List> elems = attributeAnnotationValues(tree, expectedAnnotationType, env); Attribute.Compound ac = new Attribute.Compound(tree.type, elems); return tree.attribute = ac; } /** Attribute and store a semantic representation of the type annotation tree {@code tree} into * the tree.attribute field. * * @param a the tree representing an annotation * @param expectedAnnotationType the expected (super)type of the annotation * @param env the the current env in where the annotation instance is found */ public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType, Env env) { // The attribute might have been entered if it is Target or Repetable // Because TreeCopier does not copy type, redo this if type is null if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) { // Create a new TypeCompound List> elems = attributeAnnotationValues(a, expectedAnnotationType, env); Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown); a.attribute = tc; return tc; } else { // Use an existing TypeCompound return (Attribute.TypeCompound)a.attribute; } } /** * Attribute annotation elements creating a list of pairs of the Symbol representing that * element and the value of that element as an Attribute. */ private List> attributeAnnotationValues(JCAnnotation a, Type expected, Env env) { // The annotation might have had its type attributed (but not // checked) by attr.attribAnnotationTypes during MemberEnter, // in which case we do not need to do it again. Type at = (a.annotationType.type != null ? a.annotationType.type : attr.attribType(a.annotationType, env)); a.type = chk.checkType(a.annotationType.pos(), at, expected); boolean isError = a.type.isErroneous(); if (!a.type.tsym.isAnnotationType() && !isError) { log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type)); isError = true; } // List of name=value pairs (or implicit "value=" if size 1) List args = a.args; boolean elidedValue = false; // special case: elided "value=" assumed if (args.length() == 1 && !args.head.hasTag(ASSIGN)) { args.head = make.at(args.head.pos). Assign(make.Ident(names.value), args.head); elidedValue = true; } ListBuffer> buf = new ListBuffer<>(); for (List tl = args; tl.nonEmpty(); tl = tl.tail) { Pair p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue); if (p != null && !p.fst.type.isErroneous()) buf.append(p); } return buf.toList(); } // where private Pair attributeAnnotationNameValuePair(JCExpression nameValuePair, Type thisAnnotationType, boolean badAnnotation, Env env, boolean elidedValue) { if (!nameValuePair.hasTag(ASSIGN)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } JCAssign assign = (JCAssign)nameValuePair; if (!assign.lhs.hasTag(IDENT)) { log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue); attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env); return null; } // Resolve element to MethodSym JCIdent left = (JCIdent)assign.lhs; Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(), env, thisAnnotationType, left.name, List.nil(), null); left.sym = method; left.type = method.type; if (method.owner != thisAnnotationType.tsym && !badAnnotation) log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType)); Type resultType = method.type.getReturnType(); // Compute value part Attribute value = attributeAnnotationValue(resultType, assign.rhs, env); nameValuePair.type = resultType; return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value); } /** Attribute an annotation element value */ private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree, Env env) { //first, try completing the symbol for the annotation value - if acompletion //error is thrown, we should recover gracefully, and display an //ordinary resolution diagnostic. try { expectedElementType.tsym.complete(); } catch(CompletionFailure e) { log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null)); expectedElementType = syms.errType; } if (expectedElementType.hasTag(ARRAY)) { return getAnnotationArrayValue(expectedElementType, tree, env); } //error recovery if (tree.hasTag(NEWARRAY)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } for (List l = na.elems; l.nonEmpty(); l=l.tail) { attributeAnnotationValue(syms.errType, l.head, env); } return new Attribute.Error(syms.errType); } if (expectedElementType.tsym.isAnnotationType()) { if (tree.hasTag(ANNOTATION)) { return attributeAnnotation((JCAnnotation)tree, expectedElementType, env); } else { log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation); expectedElementType = syms.errType; } } //error recovery if (tree.hasTag(ANNOTATION)) { if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType)); attributeAnnotation((JCAnnotation)tree, syms.errType, env); return new Attribute.Error(((JCAnnotation)tree).annotationType.type); } MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() { // the methods below are added to allow class literals on top of constant expressions @Override public void visitTypeIdent(JCPrimitiveTypeTree that) {} @Override public void visitTypeArray(JCArrayTypeTree that) {} }; tree.accept(initTreeVisitor); if (!initTreeVisitor.result) { log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue); return new Attribute.Error(syms.errType); } if (expectedElementType.isPrimitive() || (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) { return getAnnotationPrimitiveValue(expectedElementType, tree, env); } if (expectedElementType.tsym == syms.classType.tsym) { return getAnnotationClassValue(expectedElementType, tree, env); } if (expectedElementType.hasTag(CLASS) && (expectedElementType.tsym.flags() & Flags.ENUM) != 0) { return getAnnotationEnumValue(expectedElementType, tree, env); } //error recovery: if (!expectedElementType.isErroneous()) log.error(tree.pos(), Errors.AnnotationValueNotAllowableType); return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType)); } private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); Symbol sym = TreeInfo.symbol(tree); if (sym == null || TreeInfo.nonstaticSelect(tree) || sym.kind != VAR || (sym.flags() & Flags.ENUM) == 0) { log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant); return new Attribute.Error(result.getOriginalType()); } VarSymbol enumerator = (VarSymbol) sym; return new Attribute.Enum(expectedElementType, enumerator); } private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) { // Does it look like an unresolved class literal? if (TreeInfo.name(tree) == names._class && ((JCFieldAccess) tree).selected.type.isErroneous()) { Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName(); return new Attribute.UnresolvedClass(expectedElementType, types.createErrorType(n, syms.unknownSymbol, syms.classType)); } else { return new Attribute.Error(result.getOriginalType()); } } // Class literals look like field accesses of a field named class // at the tree level if (TreeInfo.name(tree) != names._class) { log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral); return new Attribute.Error(syms.errType); } return new Attribute.Class(types, (((JCFieldAccess) tree).selected).type); } private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env env) { Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType)); if (result.isErroneous()) return new Attribute.Error(result.getOriginalType()); if (result.constValue() == null) { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } private Attr.ResultInfo annotationValueInfo(Type pt) { return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext)); } class AnnotationValueContext extends Check.NestedCheckContext { AnnotationValueContext(CheckContext enclosingContext) { super(enclosingContext); } @Override public boolean compatible(Type found, Type req, Warner warn) { //handle non-final implicitly-typed vars (will be rejected later on) return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn); } } private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env env) { // Special case, implicit array if (!tree.hasTag(NEWARRAY)) { tree = make.at(tree.pos). NewArray(null, List.nil(), List.of(tree)); } JCNewArray na = (JCNewArray)tree; if (na.elemtype != null) { log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation); } ListBuffer buf = new ListBuffer<>(); for (List l = na.elems; l.nonEmpty(); l=l.tail) { buf.append(attributeAnnotationValue(types.elemtype(expectedElementType), l.head, env)); } na.type = expectedElementType; return new Attribute. Array(expectedElementType, buf.toArray(new Attribute[buf.length()])); } /* ********************************* * Support for repeating annotations ***********************************/ /** * This context contains all the information needed to synthesize new * annotations trees for repeating annotations. */ private class AnnotationContext { public final Env env; public final Map> annotated; public final Map pos; public final boolean isTypeCompound; public AnnotationContext(Env env, Map> annotated, Map pos, boolean isTypeCompound) { Assert.checkNonNull(env); Assert.checkNonNull(annotated); Assert.checkNonNull(pos); this.env = env; this.annotated = annotated; this.pos = pos; this.isTypeCompound = isTypeCompound; } } /* Process repeated annotations. This method returns the * synthesized container annotation or null IFF all repeating * annotation are invalid. This method reports errors/warnings. */ private T processRepeatedAnnotations(List annotations, AnnotationContext ctx, Symbol on, boolean isTypeParam) { T firstOccurrence = annotations.head; List repeated = List.nil(); Type origAnnoType = null; Type arrayOfOrigAnnoType = null; Type targetContainerType = null; MethodSymbol containerValueSymbol = null; Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1 int count = 0; for (List al = annotations; !al.isEmpty(); al = al.tail) { count++; // There must be more than a single anno in the annotation list Assert.check(count > 1 || !al.tail.isEmpty()); T currentAnno = al.head; origAnnoType = currentAnno.type; if (arrayOfOrigAnnoType == null) { arrayOfOrigAnnoType = types.makeArrayType(origAnnoType); } // Only report errors if this isn't the first occurrence I.E. count > 1 boolean reportError = count > 1; Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError); if (currentContainerType == null) { continue; } // Assert that the target Container is == for all repeated // annos of the same annotation type, the types should // come from the same Symbol, i.e. be '==' Assert.check(targetContainerType == null || currentContainerType == targetContainerType); targetContainerType = currentContainerType; containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno)); if (containerValueSymbol == null) { // Check of CA type failed // errors are already reported continue; } repeated = repeated.prepend(currentAnno); } if (!repeated.isEmpty() && targetContainerType == null) { log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); return null; } if (!repeated.isEmpty()) { repeated = repeated.reverse(); DiagnosticPosition pos = ctx.pos.get(firstOccurrence); TreeMaker m = make.at(pos); Pair p = new Pair(containerValueSymbol, new Attribute.Array(arrayOfOrigAnnoType, repeated)); if (ctx.isTypeCompound) { /* TODO: the following code would be cleaner: Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCTypeAnnotation annoTree = m.TypeAnnotation(at); at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env); */ // However, we directly construct the TypeCompound to keep the // direct relation to the contained TypeCompounds. Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p), ((Attribute.TypeCompound)annotations.head).position); JCAnnotation annoTree = m.TypeAnnotation(at); if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); if (!chk.isTypeAnnotation(annoTree, isTypeParam)) { log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on) : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType)); } at.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) at; return x; } else { Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p)); JCAnnotation annoTree = m.Annotation(c); if (!chk.annotationApplicable(annoTree, on)) { log.error(annoTree.pos(), Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)); } if (!chk.validateAnnotationDeferErrors(annoTree)) log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType)); c = attributeAnnotation(annoTree, targetContainerType, ctx.env); c.setSynthesized(true); @SuppressWarnings("unchecked") T x = (T) c; return x; } } else { return null; // errors should have been reported elsewhere } } /** * Fetches the actual Type that should be the containing annotation. */ private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable(); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType)); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); } // returns null if t is same as 's', returns 't' otherwise private Type filterSame(Type t, Type s) { if (t == null || s == null) { return t; } return types.isSameType(t, s) ? null : t; } /** Extract the actual Type to be used for a containing annotation. */ private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is repeating is // valid. // Repeatable must have at least one element if (ca.values.isEmpty()) { log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } Pair p = ca.values.head; Name name = p.fst.name; if (name != names.value) { // should contain only one element, named "value" log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl)); return null; } return ((Attribute.Class)p.snd).getValue(); } /* Validate that the suggested targetContainerType Type is a valid * container type for repeated instances of originalAnnoType * annotations. Return null and report errors if this is not the * case, return the MethodSymbol of the value element in * targetContainerType if it is suitable (this is needed to * synthesize the container). */ private MethodSymbol validateContainer(Type targetContainerType, Type originalAnnoType, DiagnosticPosition pos) { MethodSymbol containerValueSymbol = null; boolean fatalError = false; // Validate that there is a (and only 1) value method Scope scope = targetContainerType.tsym.members(); int nr_value_elems = 0; boolean error = false; for(Symbol elm : scope.getSymbolsByName(names.value)) { nr_value_elems++; if (nr_value_elems == 1 && elm.kind == MTH) { containerValueSymbol = (MethodSymbol)elm; } else { error = true; } } if (error) { log.error(pos, Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType, nr_value_elems)); return null; } else if (nr_value_elems == 0) { log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(targetContainerType)); return null; } // validate that the 'value' element is a method // probably "impossible" to fail this if (containerValueSymbol.kind != MTH) { log.error(pos, Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType)); fatalError = true; } // validate that the 'value' element has the correct return type // i.e. array of original anno Type valueRetType = containerValueSymbol.type.getReturnType(); Type expectedType = types.makeArrayType(originalAnnoType); if (!(types.isArray(valueRetType) && types.isSameType(expectedType, valueRetType))) { log.error(pos, Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType, valueRetType, expectedType)); fatalError = true; } return fatalError ? null : containerValueSymbol; } private T makeContainerAnnotation(List toBeReplaced, AnnotationContext ctx, Symbol sym, boolean isTypeParam) { // Process repeated annotations T validRepeated = processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam); if (validRepeated != null) { // Check that the container isn't manually // present along with repeated instances of // its contained annotation. ListBuffer manualContainer = ctx.annotated.get(validRepeated.type.tsym); if (manualContainer != null) { log.error(ctx.pos.get(manualContainer.first()), Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym)); } } // A null return will delete the Placeholder return validRepeated; } /******************** * Type annotations * ********************/ /** * Attribute the list of annotations and enter them onto s. */ public void enterTypeAnnotations(List annotations, Env env, Symbol s, DiagnosticPosition deferPos, boolean isTypeParam) { Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); DiagnosticPosition prevLintPos = null; if (deferPos != null) { prevLintPos = deferredLintHandler.setPos(deferPos); } try { annotateNow(s, annotations, env, true, isTypeParam); } finally { if (prevLintPos != null) deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } /** * Enqueue tree for scanning of type annotations, attaching to the Symbol sym. */ public void queueScanTreeAndTypeAnnotate(JCTree tree, Env env, Symbol sym, DiagnosticPosition deferPos) { Assert.checkNonNull(sym); normal(() -> tree.accept(new TypeAnnotate(env, sym, deferPos))); } /** * Apply the annotations to the particular type. */ public void annotateTypeSecondStage(JCTree tree, List annotations, Type storeAt) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); storeAt.getMetadataOfKind(Kind.ANNOTATIONS).combine(new TypeMetadata.Annotations(compounds)); }); } /** * Apply the annotations to the particular type. */ public void annotateTypeParameterSecondStage(JCTree tree, List annotations) { typeAnnotation(() -> { List compounds = fromAnnotations(annotations); Assert.check(annotations.size() == compounds.size()); }); } /** * We need to use a TreeScanner, because it is not enough to visit the top-level * annotations. We also need to visit type arguments, etc. */ private class TypeAnnotate extends TreeScanner { private final Env env; private final Symbol sym; private DiagnosticPosition deferPos; public TypeAnnotate(Env env, Symbol sym, DiagnosticPosition deferPos) { this.env = env; this.sym = sym; this.deferPos = deferPos; } @Override public void visitAnnotatedType(JCAnnotatedType tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); scan(tree.underlyingType); } @Override public void visitTypeParameter(JCTypeParameter tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, true); scan(tree.bounds); } @Override public void visitNewArray(JCNewArray tree) { enterTypeAnnotations(tree.annotations, env, sym, deferPos, false); for (List dimAnnos : tree.dimAnnotations) enterTypeAnnotations(dimAnnos, env, sym, deferPos, false); scan(tree.elemtype); scan(tree.elems); } @Override public void visitMethodDef(JCMethodDecl tree) { scan(tree.mods); scan(tree.restype); scan(tree.typarams); scan(tree.recvparam); scan(tree.params); scan(tree.thrown); scan(tree.defaultValue); // Do not annotate the body, just the signature. } @Override public void visitVarDef(JCVariableDecl tree) { DiagnosticPosition prevPos = deferPos; deferPos = tree.pos(); try { if (sym != null && sym.kind == VAR) { // Don't visit a parameter once when the sym is the method // and once when the sym is the parameter. scan(tree.mods); scan(tree.vartype); } scan(tree.init); } finally { deferPos = prevPos; } } @Override public void visitClassDef(JCClassDecl tree) { // We can only hit a classdef if it is declared within // a method. Ignore it - the class will be visited // separately later. } @Override public void visitNewClass(JCNewClass tree) { scan(tree.encl); scan(tree.typeargs); if (tree.def == null) { scan(tree.clazz); } scan(tree.args); // the anonymous class instantiation if any will be visited separately. } } /********************* * Completer support * *********************/ private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() { @Override public void complete(ClassSymbol sym) throws CompletionFailure { Env context = typeEnvs.get(sym); Annotate.this.attributeAnnotationType(context); } }; /* Last stage completer to enter just enough annotations to have a prototype annotation type. * This currently means entering @Target and @Repetable. */ public AnnotationTypeCompleter annotationTypeSourceCompleter() { return theSourceCompleter; } private void attributeAnnotationType(Env env) { Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(), "Trying to annotation type complete a non-annotation type"); JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JCClassDecl tree = (JCClassDecl)env.tree; AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs); v.scanAnnotationType(tree); tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable); tree.sym.getAnnotationTypeMetadata().setTarget(v.target); } finally { log.useSource(prev); } } public Attribute unfinishedDefaultValue() { return theUnfinishedDefaultValue; } public static interface AnnotationTypeCompleter { void complete(ClassSymbol sym) throws CompletionFailure; } /** Visitor to determine a prototype annotation type for a class declaring an annotation type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public class AnnotationTypeVisitor extends TreeScanner { private Env env; private final Attr attr; private final Check check; private final Symtab tab; private final TypeEnvs typeEnvs; private Compound target; private Compound repeatable; public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) { this.attr = attr; this.check = check; this.tab = tab; this.typeEnvs = typeEnvs; } public Compound getRepeatable() { return repeatable; } public Compound getTarget() { return target; } public void scanAnnotationType(JCClassDecl decl) { visitClassDef(decl); } @Override public void visitClassDef(JCClassDecl tree) { Env prevEnv = env; env = typeEnvs.get(tree.sym); try { scan(tree.mods); // look for repeatable and target // don't descend into body } finally { env = prevEnv; } } @Override public void visitAnnotation(JCAnnotation tree) { Type t = tree.annotationType.type; if (t == null) { t = attr.attribType(tree.annotationType, env); tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType); } if (t == tab.annotationTargetType) { target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env); } else if (t == tab.repeatableType) { repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env); } } } /** Represents the semantics of an Annotation Type. * * This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice. */ public static class AnnotationTypeMetadata { final ClassSymbol metaDataFor; private Compound target; private Compound repeatable; private AnnotationTypeCompleter annotationTypeCompleter; public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) { this.metaDataFor = metaDataFor; this.annotationTypeCompleter = annotationTypeCompleter; } private void init() { // Make sure metaDataFor is member entered while (!metaDataFor.isCompleted()) metaDataFor.complete(); if (annotationTypeCompleter != null) { AnnotationTypeCompleter c = annotationTypeCompleter; annotationTypeCompleter = null; c.complete(metaDataFor); } } public void complete() { init(); } public Compound getRepeatable() { init(); return repeatable; } public void setRepeatable(Compound repeatable) { Assert.checkNull(this.repeatable); this.repeatable = repeatable; } public Compound getTarget() { init(); return target; } public void setTarget(Compound target) { Assert.checkNull(this.target); this.target = target; } public Set getAnnotationElements() { init(); Set members = new LinkedHashSet<>(); WriteableScope s = metaDataFor.members(); Iterable ss = s.getSymbols(NON_RECURSIVE); for (Symbol sym : ss) if (sym.kind == MTH && sym.name != sym.name.table.names.clinit && (sym.flags() & SYNTHETIC) == 0) members.add((MethodSymbol)sym); return members; } public Set getAnnotationElementsWithDefault() { init(); Set members = getAnnotationElements(); Set res = new LinkedHashSet<>(); for (MethodSymbol m : members) if (m.defaultValue != null) res.add(m); return res; } @Override public String toString() { return "Annotation type for: " + metaDataFor; } public boolean isMetadataForAnnotationType() { return true; } public static AnnotationTypeMetadata notAnAnnotationType() { return NOT_AN_ANNOTATION_TYPE; } private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE = new AnnotationTypeMetadata(null, null) { @Override public void complete() { } // do nothing @Override public String toString() { return "Not an annotation type"; } @Override public Set getAnnotationElements() { return new LinkedHashSet<>(0); } @Override public Set getAnnotationElementsWithDefault() { return new LinkedHashSet<>(0); } @Override public boolean isMetadataForAnnotationType() { return false; } @Override public Compound getTarget() { return null; } @Override public Compound getRepeatable() { return null; } }; } public void newRound() { blockCount = 1; } }
blob long method, data class t t f long method, data class blob 0 10135 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java/#L78-L1365 1 1153 10135
67      { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } }
blob long method, data class t t f long method, data class blob 0 1077 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 1 67 1077
1468  { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } }
blob data class t t f data class blob 0 11044 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 1 1468 11044
1388    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } }
long method long method, data class t t t  data class   0 10839 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 1 1388 10839
1979 {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Command(name = "launch", description = "Starts a server, optionally with applications") public static class LaunchCommand extends BrooklynCommandWithSystemDefines { @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file", description = "Load the given properties file, specific to this launch (appending to and overriding global properties)") public String localBrooklynProperties; @Option(name = { "--noGlobalBrooklynProperties" }, title = "do not use any global brooklyn.properties file found", description = "Do not use the default global brooklyn.properties file found") public boolean noGlobalBrooklynProperties = false; @Option(name = { "-a", "--app" }, title = "application class or file", description = "The Application to start. " + "For example, my.AppName, file://my/app.yaml, or classpath://my/AppName.groovy -- " + "note that a BROOKLYN_CLASSPATH environment variable may be required to " + "load classes from other locations") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load." + " This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched. " + "You can specify more than one location as a comma-separated list of values " + "(or as a JSON array, if the values are complex)") public String locations; @Option(name = { "--catalogInitial" }, title = "catalog initial bom URI", description = "Specifies a catalog.bom URI to be used to populate the initial catalog, " + "loaded on first run, or when persistence is off/empty or the catalog is reset") public String catalogInitial; @Option(name = { "--catalogReset" }, description = "Specifies that any catalog items which have been persisted should be cleared") public boolean catalogReset; @Option(name = { "--catalogAdd" }, title = "catalog bom URI to add", description = "Specifies a catalog.bom to be added to the catalog") public String catalogAdd; @Option(name = { "--catalogForce" }, description = "Specifies that catalog items added via the CLI should be forcibly added, " + "replacing any identical versions already registered (use with care!)") public boolean catalogForce; @Option(name = { "-p", "--port" }, title = "port number", description = "Use this port for the brooklyn management web console and REST API; " + "default is 8081+ for http, 8443+ for https.") public String port; @Option(name = { "--https" }, description = "Launch the web console on https") public boolean useHttps = false; @Option(name = { "-nc", "--noConsole" }, description = "Do not start the web console or REST API") public boolean noConsole = false; @Option(name = { "-b", "--bindAddress" }, description = "Specifies the IP address of the NIC to bind the Brooklyn Management Console to") public String bindAddress = null; @Option(name = { "-pa", "--publicAddress" }, description = "Specifies the IP address or hostname that the Brooklyn Management Console will be available on") public String publicAddress = null; @Option(name = { "--noConsoleSecurity" }, description = "Whether to disable authentication and security filters for the web console (for use when debugging on a secure network or bound to localhost)") public Boolean noConsoleSecurity = false; @Option(name = { "--startupContinueOnWebErrors" }, description = "Continue on web subsystem failures during startup " + "(default is to abort if the web API fails to start, as management access is not normally possible)") public boolean startupContinueOnWebErrors = false; @Option(name = { "--startupFailOnPersistenceErrors" }, description = "Fail on persistence/HA subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnPersistenceErrors = false; @Option(name = { "--startupFailOnCatalogErrors" }, description = "Fail on catalog subsystem failures during startup " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnCatalogErrors = false; @Option(name = { "--startupFailOnManagedAppsErrors" }, description = "Fail startup on errors deploying of managed apps specified via the command line " + "(default is to continue, so errors can be viewed via the API)") public boolean startupFailOnManagedAppsErrors = false; @Beta @Option(name = { "--startBrooklynNode" }, description = "Start a BrooklynNode entity representing this Brooklyn instance") public boolean startBrooklynNode = false; // Note in some cases, you can get java.util.concurrent.RejectedExecutionException // if shutdown is not co-ordinated, looks like: {@linktourl https://gist.github.com/47066f72d6f6f79b953e} @Beta @Option(name = { "-sk", "--stopOnKeyPress" }, description = "Shutdown immediately on user text entry after startup (useful for debugging and demos)") public boolean stopOnKeyPress = false; final static String STOP_WHICH_APPS_ON_SHUTDOWN = "--stopOnShutdown"; protected final static String STOP_ALL = "all"; protected final static String STOP_ALL_IF_NOT_PERSISTED = "allIfNotPersisted"; protected final static String STOP_NONE = "none"; protected final static String STOP_THESE = "these"; protected final static String STOP_THESE_IF_NOT_PERSISTED = "theseIfNotPersisted"; static { Enums.checkAllEnumeratedIgnoreCase(StopWhichAppsOnShutdown.class, STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED); } @Option(name = { STOP_WHICH_APPS_ON_SHUTDOWN }, allowedValues = { STOP_ALL, STOP_ALL_IF_NOT_PERSISTED, STOP_NONE, STOP_THESE, STOP_THESE_IF_NOT_PERSISTED }, description = "Which managed applications to stop on shutdown. Possible values are:\n"+ "all: stop all apps\n"+ "none: leave all apps running\n"+ "these: stop the apps explicitly started on this command line, but leave others started subsequently running\n"+ "theseIfNotPersisted: stop the apps started on this command line IF persistence is not enabled, otherwise leave all running\n"+ "allIfNotPersisted: stop all apps IF persistence is not enabled, otherwise leave all running") public String stopWhichAppsOnShutdown = STOP_THESE_IF_NOT_PERSISTED; @Option(name = { "--exitAndLeaveAppsRunningAfterStarting" }, description = "Once the application to start (from --app) is running exit the process, leaving any entities running. " + "Can be used in combination with --persist auto --persistenceDir to attach to the running app at a later time.") public boolean exitAndLeaveAppsRunningAfterStarting = false; final static String PERSIST_OPTION = "--persist"; protected final static String PERSIST_OPTION_DISABLED = "disabled"; protected final static String PERSIST_OPTION_AUTO = "auto"; protected final static String PERSIST_OPTION_REBIND = "rebind"; protected final static String PERSIST_OPTION_CLEAN = "clean"; static { Enums.checkAllEnumeratedIgnoreCase(PersistMode.class, PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN); } // TODO currently defaults to disabled; want it to default to on, when we're ready // TODO how to force a line-split per option?! // Looks like java.io.airlift.airline.UsagePrinter is splitting the description by word, and // wrapping it automatically. // See https://github.com/airlift/airline/issues/30 @Option(name = { PERSIST_OPTION }, allowedValues = { PERSIST_OPTION_DISABLED, PERSIST_OPTION_AUTO, PERSIST_OPTION_REBIND, PERSIST_OPTION_CLEAN }, title = "persistence mode", description = "The persistence mode. Possible values are: \n"+ "disabled: will not read or persist any state; \n"+ "auto: will rebind to any existing state, or start up fresh if no state; \n"+ "rebind: will rebind to the existing state, or fail if no state available; \n"+ "clean: will start up fresh (removing any existing state)") public String persist = PERSIST_OPTION_DISABLED; @Option(name = { "--persistenceDir" }, title = "persistence dir", description = "The directory to read/write persisted state (or container name if using an object store)") public String persistenceDir; @Option(name = { "--persistenceLocation" }, title = "persistence location", description = "The location spec for an object store to read/write persisted state") public String persistenceLocation; final static String HA_OPTION = "--highAvailability"; protected final static String HA_OPTION_DISABLED = "disabled"; protected final static String HA_OPTION_AUTO = "auto"; protected final static String HA_OPTION_MASTER = "master"; protected final static String HA_OPTION_STANDBY = "standby"; protected final static String HA_OPTION_HOT_STANDBY = "hot_standby"; protected final static String HA_OPTION_HOT_BACKUP = "hot_backup"; static { Enums.checkAllEnumeratedIgnoreCase(HighAvailabilityMode.class, HA_OPTION_AUTO, HA_OPTION_DISABLED, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP); } @Option(name = { HA_OPTION }, allowedValues = { HA_OPTION_DISABLED, HA_OPTION_AUTO, HA_OPTION_MASTER, HA_OPTION_STANDBY, HA_OPTION_HOT_STANDBY, HA_OPTION_HOT_BACKUP }, title = "high availability mode", description = "The high availability mode. Possible values are: \n"+ "disabled: management node works in isolation - will not cooperate with any other standby/master nodes in management plane; \n"+ "auto: will look for other management nodes, and will allocate itself as standby or master based on other nodes' states; \n"+ "master: will startup as master - if there is already a master then fails immediately; \n"+ "standby: will start up as lukewarm standby with no state - if there is not already a master then fails immediately, " + "and if there is a master which subsequently fails, this node can promote itself; \n"+ "hot_standby: will start up as hot standby in read-only mode - if there is not already a master then fails immediately, " + "and if there is a master which subseuqently fails, this node can promote itself; \n"+ "hot_backup: will start up as hot backup in read-only mode - no master is required, and this node will not become a master" ) public String highAvailability = HA_OPTION_AUTO; @VisibleForTesting protected ManagementContext explicitManagementContext; @Override public Void call() throws Exception { super.call(); // Configure launcher BrooklynLauncher launcher; AppShutdownHandler shutdownHandler = new AppShutdownHandler(); failIfArguments(); try { if (log.isDebugEnabled()) log.debug("Invoked launch command {}", this); if (!quiet) stdout.println(banner); if (verbose) { if (app != null) { stdout.println("Launching brooklyn app: " + app + " in " + locations); } else { stdout.println("Launching brooklyn server (no app)"); } } PersistMode persistMode = computePersistMode(); HighAvailabilityMode highAvailabilityMode = computeHighAvailabilityMode(persistMode); StopWhichAppsOnShutdown stopWhichAppsOnShutdownMode = computeStopWhichAppsOnShutdown(); computeLocations(); ResourceUtils utils = ResourceUtils.create(this); GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // First, run a setup script if the user has provided one if (script != null) { execGroovyScript(utils, loader, script); } launcher = createLauncher(); CatalogInitialization catInit = new CatalogInitialization(catalogInitial, catalogReset, catalogAdd, catalogForce); catInit.addPopulationCallback(new Function() { @Override public Void apply(CatalogInitialization catInit) { try { populateCatalog(catInit.getManagementContext().getCatalog()); } catch (Throwable e) { catInit.handleException(e, "overridden main class populate catalog"); } // Force load of catalog (so web console is up to date) confirmCatalog(catInit); return null; } }); catInit.setFailOnStartupErrors(startupFailOnCatalogErrors); launcher.catalogInitialization(catInit); launcher.persistMode(persistMode); launcher.persistenceDir(persistenceDir); launcher.persistenceLocation(persistenceLocation); launcher.highAvailabilityMode(highAvailabilityMode); launcher.stopWhichAppsOnShutdown(stopWhichAppsOnShutdownMode); launcher.shutdownHandler(shutdownHandler); computeAndSetApp(launcher, utils, loader); customize(launcher); } catch (FatalConfigurationRuntimeException e) { throw e; } catch (Exception e) { throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e); } // Launch server try { launcher.start(); } catch (FatalRuntimeException e) { // rely on caller logging this propagated exception throw e; } catch (Exception e) { // for other exceptions we log it, possibly redundantly but better too much than too little Exceptions.propagateIfFatal(e); log.error("Error launching brooklyn: "+Exceptions.collapseText(e), e); try { launcher.terminate(); } catch (Exception e2) { log.warn("Subsequent error during termination: "+e2); log.debug("Details of subsequent error during termination: "+e2, e2); } Exceptions.propagate(e); } BrooklynServerDetails server = launcher.getServerDetails(); ManagementContext mgmt = server.getManagementContext(); if (verbose) { Entities.dumpInfo(launcher.getApplications()); } if (!exitAndLeaveAppsRunningAfterStarting) { waitAfterLaunch(mgmt, shutdownHandler); } // do not shutdown servers here here -- // the BrooklynShutdownHookJob will invoke that and others on System.exit() // which happens immediately after. // might be nice to do it explicitly here, // but the server shutdown process has some special "shutdown apps" options // so we'd want to refactor BrooklynShutdownHookJob to share code return null; } /** can be overridden by subclasses which need to customize the launcher and/or management */ protected void customize(BrooklynLauncher launcher) { } protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence; this behaviour may change in subsequent versions"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } } protected boolean isYamlApp() { return app != null && app.endsWith(".yaml"); } protected PersistMode computePersistMode() { Maybe persistMode = Enums.valueOfIgnoreCase(PersistMode.class, persist); if (!persistMode.isPresent()) { if (Strings.isBlank(persist)) { throw new FatalConfigurationRuntimeException("Persist mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal persist setting: "+persist); } } if (persistMode.get() == PersistMode.DISABLED) { if (Strings.isNonBlank(persistenceDir)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceDir when persist is disabled"); if (Strings.isNonBlank(persistenceLocation)) throw new FatalConfigurationRuntimeException("Cannot specify persistenceLocation when persist is disabled"); } return persistMode.get(); } protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) { Maybe highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability); if (!highAvailabilityMode.isPresent()) { if (Strings.isBlank(highAvailability)) { throw new FatalConfigurationRuntimeException("High availability mode must not be blank"); } else { throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability); } } if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) { if (persistMode == PersistMode.DISABLED) { if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO) return HighAvailabilityMode.DISABLED; throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled"); } else if (persistMode == PersistMode.CLEAN && (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) { throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN"); } } return highAvailabilityMode.get(); } protected StopWhichAppsOnShutdown computeStopWhichAppsOnShutdown() { boolean isDefault = STOP_THESE_IF_NOT_PERSISTED.equals(stopWhichAppsOnShutdown); if (exitAndLeaveAppsRunningAfterStarting && isDefault) { return StopWhichAppsOnShutdown.NONE; } else { return Enums.valueOfIgnoreCase(StopWhichAppsOnShutdown.class, stopWhichAppsOnShutdown).get(); } } @VisibleForTesting /** forces the launcher to use the given management context, when programmatically invoked; * mainly used when testing to inject a safe (and fast) mgmt context */ public void useManagementContext(ManagementContext mgmt) { explicitManagementContext = mgmt; } protected BrooklynLauncher createLauncher() { BrooklynLauncher launcher; launcher = BrooklynLauncher.newInstance(); launcher.localBrooklynPropertiesFile(localBrooklynProperties) .ignorePersistenceErrors(!startupFailOnPersistenceErrors) .ignoreCatalogErrors(!startupFailOnCatalogErrors) .ignoreWebErrors(startupContinueOnWebErrors) .ignoreAppErrors(!startupFailOnManagedAppsErrors) .locations(Strings.isBlank(locations) ? ImmutableList.of() : JavaStringEscapes.unwrapJsonishListIfPossible(locations)); launcher.webconsole(!noConsole); if (useHttps) { // true sets it; false (not set) leaves it blank and falls back to config key // (no way currently to override config key, but that could be added) launcher.webconsoleHttps(useHttps); } launcher.webconsolePort(port); if (noGlobalBrooklynProperties) { log.debug("Configuring to disable global brooklyn.properties"); launcher.globalBrooklynPropertiesFile(null); } if (noConsoleSecurity) { log.info("Configuring to disable console security"); launcher.installSecurityFilter(false); } if (startBrooklynNode) { log.info("Configuring BrooklynNode entity startup"); launcher.startBrooklynNode(true); } if (Strings.isNonEmpty(bindAddress)) { log.debug("Configuring bind address as "+bindAddress); launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress)); } if (Strings.isNonEmpty(publicAddress)) { log.debug("Configuring public address as "+publicAddress); launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress)); } if (explicitManagementContext!=null) { log.debug("Configuring explicit management context "+explicitManagementContext); launcher.managementContext(explicitManagementContext); } return launcher; } /** method intended for subclassing, to add custom items to the catalog */ protected void populateCatalog(BrooklynCatalog catalog) { // nothing else added here } protected void confirmCatalog(CatalogInitialization catInit) { // Force load of catalog (so web console is up to date) Stopwatch time = Stopwatch.createStarted(); BrooklynCatalog catalog = catInit.getManagementContext().getCatalog(); Iterable> items = catalog.getCatalogItems(); for (CatalogItem item: items) { try { if (item.getCatalogItemType()==CatalogItemType.TEMPLATE) { // skip validation of templates, they might contain instructions, // and additionally they might contain multiple items in which case // the validation below won't work anyway (you need to go via a deployment plan) } else { @SuppressWarnings({ "unchecked", "rawtypes" }) Object spec = catalog.createSpec((CatalogItem)item); if (spec instanceof EntitySpec) { BrooklynTypes.getDefinedEntityType(((EntitySpec)spec).getType()); } log.debug("Catalog loaded spec "+spec+" for item "+item); } } catch (Throwable throwable) { catInit.handleException(throwable, item); } } log.debug("Catalog (size "+Iterables.size(items)+") confirmed in "+Duration.of(time)); // nothing else added here } /** convenience for subclasses to specify that an app should run, * throwing the right (caught) error if another app has already been specified */ protected void setAppToLaunch(String className) { if (app!=null) { if (app.equals(className)) return; throw new FatalConfigurationRuntimeException("Cannot specify app '"+className+"' when '"+app+"' is already specified; " + "remove one or more conflicting CLI arguments."); } app = className; } protected void computeAndSetApp(BrooklynLauncher launcher, ResourceUtils utils, GroovyClassLoader loader) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (app != null) { // Create the instance of the brooklyn app log.debug("Loading the user's application: {}", app); if (isYamlApp()) { log.debug("Loading application as YAML spec: {}", app); String content = utils.getResourceAsString(app); launcher.application(content); } else { Object loadedApp = loadApplicationFromClasspathOrParse(utils, loader, app); if (loadedApp instanceof ApplicationBuilder) { launcher.application((ApplicationBuilder)loadedApp); } else if (loadedApp instanceof Application) { launcher.application((AbstractApplication)loadedApp); } else { throw new FatalConfigurationRuntimeException("Unexpected application type "+(loadedApp==null ? null : loadedApp.getClass())+", for app "+loadedApp); } } } } protected void waitAfterLaunch(ManagementContext ctx, AppShutdownHandler shutdownHandler) throws IOException { if (stopOnKeyPress) { // Wait for the user to type a key log.info("Server started. Press return to stop."); // Read in another thread so we can use timeout on the wait. Task readTask = ctx.getExecutionManager().submit(new Callable() { @Override public Void call() throws Exception { stdin.read(); return null; } }); while (!shutdownHandler.isRequested()) { try { readTask.get(Duration.ONE_SECOND); break; } catch (TimeoutException e) { //check if there's a shutdown request } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Exceptions.propagate(e); } catch (ExecutionException e) { throw Exceptions.propagate(e); } } log.info("Shutting down applications."); stopAllApps(ctx.getApplications()); } else { // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) log.info("Launched Brooklyn; will now block until shutdown command received via GUI/API (recommended) or process interrupt."); shutdownHandler.waitOnShutdownRequest(); } } protected void execGroovyScript(ResourceUtils utils, GroovyClassLoader loader, String script) { log.debug("Running the user provided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } /** * Helper method that gets an instance of a brooklyn {@link AbstractApplication} or an {@link ApplicationBuilder}. * Guaranteed to be non-null result of one of those types (throwing exception if app not appropriate). */ @SuppressWarnings("unchecked") protected Object loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class tempclazz; log.debug("Loading application as class on classpath: {}", app); try { tempclazz = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file", app); String content = utils.getResourceAsString(app); tempclazz = loader.parseClass(content); } final Class clazz = tempclazz; // Instantiate an app builder (wrapping app class in ApplicationBuilder, if necessary) if (ApplicationBuilder.class.isAssignableFrom(clazz)) { Constructor constructor = clazz.getConstructor(); return (ApplicationBuilder) constructor.newInstance(); } else if (StartableApplication.class.isAssignableFrom(clazz)) { EntitySpec appSpec; if (tempclazz.isInterface()) appSpec = EntitySpec.create((Class) clazz); else appSpec = EntitySpec.create(StartableApplication.class, (Class) clazz); return new ApplicationBuilder(appSpec) { @Override protected void doBuild() { }}; } else if (AbstractApplication.class.isAssignableFrom(clazz)) { // TODO If this application overrides init() then in trouble, as that won't get called! // TODO grr; what to do about non-startable applications? // without this we could return ApplicationBuilder rather than Object Constructor constructor = clazz.getConstructor(); return (AbstractApplication) constructor.newInstance(); } else if (AbstractEntity.class.isAssignableFrom(clazz)) { // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented! return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create(Entity.class).impl((Class)clazz).additionalInterfaces(clazz.getInterfaces())); }}; } else if (Entity.class.isAssignableFrom(clazz)) { return new ApplicationBuilder() { @Override protected void doBuild() { addChild(EntitySpec.create((Class)clazz)); }}; } else { throw new FatalConfigurationRuntimeException("Application class "+clazz+" must extend one of ApplicationBuilder or AbstractApplication"); } } @VisibleForTesting protected void stopAllApps(Collection applications) { for (Application application : applications) { try { if (application instanceof Startable) { ((Startable)application).stop(); } } catch (Exception e) { log.error("Error stopping "+application+": "+e, e); } } } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("bindAddress", bindAddress) .add("noConsole", noConsole) .add("noConsoleSecurity", noConsoleSecurity) .add("startupFailOnPersistenceErrors", startupFailOnPersistenceErrors) .add("startupFailsOnCatalogErrors", startupFailOnCatalogErrors) .add("startupContinueOnWebErrors", startupContinueOnWebErrors) .add("startupFailOnManagedAppsErrors", startupFailOnManagedAppsErrors) .add("catalogInitial", catalogInitial) .add("catalogAdd", catalogAdd) .add("catalogReset", catalogReset) .add("catalogForce", catalogForce) .add("stopWhichAppsOnShutdown", stopWhichAppsOnShutdown) .add("stopOnKeyPress", stopOnKeyPress) .add("localBrooklynProperties", localBrooklynProperties) .add("persist", persist) .add("persistenceLocation", persistenceLocation) .add("persistenceDir", persistenceDir) .add("highAvailability", highAvailability) .add("exitAndLeaveAppsRunningAfterStarting", exitAndLeaveAppsRunningAfterStarting); } }
blob long method, data class t t f long method, data class blob 0 12634 https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java/#L194-L824 1 1979 12634
1184  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class LdapProtocolUtils { /** A delimiter for the replicaId */ public static final String COOKIE_DELIM = ","; /** the prefix for replicaId value */ public static final String REPLICA_ID_PREFIX = "rid="; public static final int REPLICA_ID_PREFIX_LEN = REPLICA_ID_PREFIX.length(); /** the prefix for Csn value */ public static final String CSN_PREFIX = "csn="; private static final int CSN_PREFIX_LEN = CSN_PREFIX.length(); private static final Logger LOG = LoggerFactory.getLogger( LdapProtocolUtils.class ); private LdapProtocolUtils() { } /** * Extracts request controls from a request to populate into an * OperationContext. * * @param opContext the context to populate with request controls * @param request the request to extract controls from */ public static void setRequestControls( OperationContext opContext, Request request ) { if ( request.getControls() != null ) { opContext .addRequestControls( request.getControls().values().toArray( LdapProtocolConstants.EMPTY_CONTROLS ) ); } } /** * Extracts response controls from a an OperationContext to populate into * a Response object. * * @param opContext the context to extract controls from * @param response the response to populate with response controls */ public static void setResponseControls( OperationContext opContext, Response response ) { response.addAllControls( opContext.getResponseControls() ); } public static byte[] createCookie( int replicaId, String csn ) { // the syncrepl cookie format (compatible with OpenLDAP) // rid=nn,csn=xxxz String replicaIdStr = StringUtils.leftPad( Integer.toString( replicaId ), 3, '0' ); return Strings.getBytesUtf8( REPLICA_ID_PREFIX + replicaIdStr + COOKIE_DELIM + CSN_PREFIX + csn ); } /** * Check the cookie syntax. A cookie must have the following syntax : * { rid={replicaId},csn={CSN} } * * @param cookieString The cookie * @return true if the cookie is valid */ public static boolean isValidCookie( String cookieString ) { if ( ( cookieString == null ) || ( cookieString.trim().length() == 0 ) ) { return false; } int pos = cookieString.indexOf( COOKIE_DELIM ); // position should start from REPLICA_ID_PREFIX_LEN or higher cause a cookie can be // like "rid=0,csn={csn}" or "rid=11,csn={csn}" if ( pos <= REPLICA_ID_PREFIX_LEN ) { return false; } String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, pos ); try { Integer.parseInt( replicaId ); } catch ( NumberFormatException e ) { LOG.debug( "Failed to parse the replica id {}", replicaId ); return false; } if ( pos == cookieString.length() ) { return false; } String csnString = cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); return Csn.isValid( csnString ); } /** * returns the CSN present in cookie * * @param cookieString the cookie * @return The CSN */ public static String getCsn( String cookieString ) { int pos = cookieString.indexOf( COOKIE_DELIM ); return cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); } /** * returns the replica id present in cookie * * @param cookieString the cookie * @return The replica Id */ public static int getReplicaId( String cookieString ) { String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, cookieString.indexOf( COOKIE_DELIM ) ); return Integer.parseInt( replicaId ); } }
blob long method, data class t t f long method, data class blob 0 10239 https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolUtils.java/#L38-L171 1 1184 10239
2043 {"response":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } }
blob long method, data class t t f long method, data class blob 0 12862 https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 1 2043 12862
1015 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class KafkaTestServer { public static final int CACHE_TTL_MS = 1; private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestServer.class); private int kafkaPort = -1; private TestingServer zkServer; private KafkaServerStartable kafkaServer = null; private File sentrySitePath = null; public KafkaTestServer(File sentrySitePath) throws Exception { this.sentrySitePath = sentrySitePath; createZkServer(); this.kafkaPort = TestUtils.getFreePort(); createKafkaServer(); } public void start() throws Exception { kafkaServer.startup(); LOGGER.info("Started Kafka broker."); } public void shutdown() { if (kafkaServer != null) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); LOGGER.info("Stopped Kafka server."); } if (zkServer != null) { try { zkServer.stop(); LOGGER.info("Stopped ZK server."); } catch (IOException e) { LOGGER.error("Failed to shutdown ZK server.", e); } } } private Path getTempDirectory() { Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory("kafka-sentry-"); } catch (IOException e) { LOGGER.error("Failed to create temp dir for Kafka's log dir."); throw new RuntimeException(e); } return tempDirectory; } private void setupKafkaProps(Properties props) throws UnknownHostException { props.put("listeners", "SSL://" + InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort); props.put("log.dir", getTempDirectory().toAbsolutePath().toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controller.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", true); props.put("delete.topic.enable", false); props.put("controlled.shutdown.retry.backoff.ms", "100"); props.put("port", kafkaPort); props.put("offsets.topic.replication.factor", "1"); props.put("authorizer.class.name", "org.apache.sentry.kafka.authorizer.SentryKafkaAuthorizer"); props.put("sentry.kafka.site.url", "file://" + sentrySitePath.getAbsolutePath()); props.put("allow.everyone.if.no.acl.found", "true"); props.put("ssl.keystore.location", KafkaTestServer.class.getResource("/test.keystore.jks").getPath()); props.put("ssl.keystore.password", "test-ks-passwd"); props.put("ssl.key.password", "test-key-passwd"); props.put("ssl.truststore.location", KafkaTestServer.class.getResource("/test.truststore.jks").getPath()); props.put("ssl.truststore.password", "test-ts-passwd"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); props.put(KafkaAuthConf.KAFKA_SUPER_USERS, "User:CN=superuser;User:CN=superuser1; User:CN=Superuser2 "); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_ENABLE_NAME, "true"); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_TTL_MS_NAME, String.valueOf(CACHE_TTL_MS)); } private void createKafkaServer() throws UnknownHostException { Properties props = new Properties(); setupKafkaProps(props); kafkaServer = KafkaServerStartable.fromProps(props); } private void createZkServer() throws Exception { try { zkServer = new TestingServer(); } catch (Exception e) { LOGGER.error("Failed to create testing zookeeper server."); throw new RuntimeException(e); } } public String getBootstrapServers() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort; } }
blob long method, blob, data class t t t long method, data class   0 9297 https://github.com/apache/sentry/blob/f859446b65bbc274bc4899464892151eec8217c6/sentry-tests/sentry-tests-kafka/src/main/java/org/apache/sentry/tests/e2e/kafka/KafkaTestServer.java/#L35-L129 1 1015 9297
2457   YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions 4. Code duplication 5. Data class 6. Shotgun surgery 7. Speculative generality 8. Message chains 9. Temporary field 10. Data clumps 11. Primitive obsession 12. Inappropriate intimacy I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } }
blob  Long method 2 Feature envy 3 Inconsistent naming conventions 4 Code duplication 5 Data class 6 Shotgun surgery 7 Speculative generality 8 Message chains 9 Temporary field t f f . Long method 2. Feature envy 3. Inconsistent naming conventions 4. Code duplication 5. Data class 6. Shotgun surgery 7. Speculative generality 8. Message chains 9. Temporary field blob 0 14527 https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 2 2457 14527
5763   YES I found bad smells, the bad smells are: 1. Long method 2. Data class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } }
feature envy  Long method2 Data class t f f . Long method2. Data class feature envy 0 14545 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 1 5763 14545
331 { "response": "YES I found bad smells", "bad_smells": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Expression setUpper(Bound newUpper) { upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive); return this; }
feature envy data class t t f data class feature envy 0 3397 https://github.com/apache/cassandra/blob/e191aff385053bdb5325f15bc6d16d2dc0ee0589/src/java/org/apache/cassandra/index/sasi/plan/Expression.java/#L127-L131 1 331 3397
620 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; }
long method long method, data class t t t  data class   0 6215 https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 1 620 6215
183 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } }
blob data class, long method t t f data class, long method blob 0 2095 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 1 183 2095
755    { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; }
long method blob, data class, long method t t t blob, data class   0 7047 https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 1 755 7047
118 { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override @NonNull public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; }
feature envy long method, data class t t f long method, data class feature envy 0 1509 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java/#L426-L430 1 118 1509
1318    { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } }
feature envy data class, long method t t f data class, long method feature envy 0 10692 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 1 1318 10692
2684     { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); }
feature envy long method, data class t t f long method, data class feature envy 0 15270 https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 1 2684 15270
3707      { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; }
long method 1. long method, 2. data class t t t  2. data class   0 8853 https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 1 3707 8853
579  { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; }
long method long method, data class t t t  data class   0 5784 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 1 579 5784
1670  {"output": "YES I found bad smells the bad smells are: \n1. Blob, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } }
blob \n1. blob, 2. data class t t t  2. data class   0 11632 https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 1 1670 11632
1380 {"response":"YES I found bad smells","the bad smells are":["1. Long Method","2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ModuleOptionsReferenceDoc { /** * Matches "//^." exactly. */ private static final Pattern FENCE_START_REGEX = Pattern.compile("^//\\^([^.]+)\\.([^.]+)$"); private ModuleRegistry moduleRegistry = new ResourceModuleRegistry("file:./modules"); private ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver(); private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public static void main(String... paths) throws IOException { ModuleOptionsReferenceDoc runner = new ModuleOptionsReferenceDoc(); for (String path : paths) { runner.updateSingleFile(path); } } private void updateSingleFile(String path) throws IOException { File originalFile = new File(path); Assert.isTrue(originalFile.exists() && !originalFile.isDirectory(), String.format("'%s' does not exist or points to a directory", originalFile.getAbsolutePath())); File backup = new File(originalFile.getAbsolutePath() + ".backup"); originalFile.renameTo(backup); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(backup), "UTF-8")); PrintStream out = new PrintStream(new FileOutputStream(originalFile), false, "UTF-8"); ModuleType type = null; String name = null; int openingLineNumber = 0; int ln = 1; for (String line = reader.readLine(); line != null; line = reader.readLine(), ln++) { Matcher startMatcher = FENCE_START_REGEX.matcher(line); if (startMatcher.matches()) { checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); type = ModuleType.valueOf(startMatcher.group(1)); name = startMatcher.group(2); openingLineNumber = ln; out.println(line); } else if (type != null && line.equals(String.format("//$%s.%s", type, name))) { generateWarning(out, name, type); generateAsciidoc(out, name, type); type = null; name = null; out.println(line); } else if (type == null) { out.println(line); } } checkPreviousTagHasBeenClosed(originalFile, backup, out, type, name, openingLineNumber); out.close(); reader.close(); backup.delete(); } private void checkPreviousTagHasBeenClosed(File originalFile, File backup, PrintStream out, ModuleType type, String name, int openingLineNumber) { if (type != null) { out.close(); originalFile.delete(); backup.renameTo(originalFile); throw new IllegalStateException(String.format( "In %s, found '//^%s.%s' @line %d with no matching '//$%2$s.%3$s'", originalFile.getAbsolutePath(), type, name, openingLineNumber)); } } private void generateWarning(PrintStream out, String name, ModuleType type) { out.format("// DO NOT MODIFY THE LINES BELOW UNTIL THE CLOSING '//$%s.%s' TAG%n", type, name); out.format("// THIS SNIPPET HAS BEEN GENERATED BY %s AND MANUAL EDITS WILL BE LOST%n", ModuleOptionsReferenceDoc.class.getSimpleName()); } private void generateAsciidoc(PrintStream out, String name, ModuleType type) throws IOException { ModuleDefinition def = moduleRegistry.findDefinition(name, type); ModuleOptionsMetadata moduleOptionsMetadata = moduleOptionsMetadataResolver.resolve(def); Resource moduleLoc = resourcePatternResolver.getResource(((SimpleModuleDefinition) def).getLocation()); ClassLoader moduleClassLoader = ModuleUtils.createModuleDiscoveryClassLoader(moduleLoc, ModuleOptionsReferenceDoc.class.getClassLoader()); if (!moduleOptionsMetadata.iterator().hasNext()) { out.format("The **%s** %s has no particular option (in addition to options shared by all modules)%n%n", pt(def.getName()), pt(def.getType())); return; } out.format("The **%s** %s has the following options:%n%n", pt(def.getName()), pt(def.getType())); List options = new ArrayList(); for (ModuleOption mo : moduleOptionsMetadata) { options.add(mo); } Collections.sort(options, new Comparator() { @Override public int compare(ModuleOption o1, ModuleOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (ModuleOption mo : options) { String prettyDefault = prettifyDefaultValue(mo); String maybeEnumHint = generateEnumValues(mo, moduleClassLoader); out.format("%s:: %s *(%s, %s%s)*%n", pt(mo.getName()), pt(mo.getDescription()), pt(shortClassName(mo.getType())), prettyDefault, maybeEnumHint); } } private String shortClassName(String fqName) { int lastDot = fqName.lastIndexOf('.'); return lastDot >= 0 ? fqName.substring(lastDot + 1) : fqName; } /** * When the type of an option is an enum, document all possible values */ private String generateEnumValues(ModuleOption mo, ClassLoader moduleClassLoader) { // Attempt to convert back to com.acme.Foo$Bar form String canonical = mo.getType(); String system = canonical.replaceAll("(.*\\p{Upper}[^\\.]*)\\.(\\p{Upper}.*)", "$1\\$$2"); Class clazz = null; try { clazz = Class.forName(system, false, moduleClassLoader); } catch (ClassNotFoundException e) { return ""; } if (Enum.class.isAssignableFrom(clazz)) { String values = StringUtils.arrayToCommaDelimitedString(clazz.getEnumConstants()); return String.format(", possible values: `%s`", values); } else return ""; } private String prettifyDefaultValue(ModuleOption mo) { if (mo.getDefaultValue() == null) { return "no default"; } String result = stringify(mo.getDefaultValue()); result = result.replace(ModulePlaceholders.XD_STREAM_NAME, ""); result = result.replace(ModulePlaceholders.XD_JOB_NAME, ""); return "default: `" + result + "`"; } private String stringify(Object element) { Class clazz = element.getClass(); if (clazz == byte[].class) { return Arrays.toString((byte[]) element); } else if (clazz == short[].class) { return Arrays.toString((short[]) element); } else if (clazz == int[].class) { return Arrays.toString((int[]) element); } else if (clazz == long[].class) { return Arrays.toString((long[]) element); } else if (clazz == char[].class) { return Arrays.toString((char[]) element); } else if (clazz == float[].class) { return Arrays.toString((float[]) element); } else if (clazz == double[].class) { return Arrays.toString((double[]) element); } else if (clazz == boolean[].class) { return Arrays.toString((boolean[]) element); } else if (element instanceof Object[]) { return Arrays.deepToString((Object[]) element); } else { return element.toString(); } } /** * Return an asciidoc passthrough version of some text, in case the original text contains characters * that would be (mis)interpreted by asciidoc. */ private String pt(Object original) { return "$$" + original + "$$"; } }
blob '1. Long Method', '2. Data Class' t t f {',1,.," ",L,o,n,g," ",M,e,t,h,o,d,',","," ",',2,.," ",D,a,t,a," ",C,l,a,s,s,'} {',1,.," ",o,n,g," ",M,t,h,o,d,',","," ",',2,.," ",D,t," ",C,'} 0 10819 https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/documentation-toolchain/src/main/java/org/springframework/xd/documentation/ModuleOptionsReferenceDoc.java/#L62-L260 1 1380 10819
1980 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } }
blob data class, long method t t f data class, long method blob 0 12638 https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 1 1980 12638
1856 { "output": "YES I found bad smells\nthe bad smells are: 1. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } }
blob 1. data class t t f 1. data class blob 0 12215 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 1 1856 12215
3053 {"response": "YES I found bad smells the bad smells are:1. Long Method, 2. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 3501 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 1 3053 3501
2203      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; }
long method long method, data class t t t  data class   0 13507 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 1 2203 13507
2334  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } }
blob long method, data class t t f long method, data class blob 0 14160 https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 1 2334 14160
1826 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } }
long method Long Method, Data Class t f t  Data Class   0 12112 https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 1 1826 12112
1838        { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } }
feature envy Long Method, Data Class t f f Long Method, Data Class feature envy 0 12143 https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 1 1838 12143
161  { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); }
feature envy long method, data class t t f long method, data class feature envy 0 1994 https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 1 161 1994
1872    { "response": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } }
blob data class t t f data class blob 0 12250 https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 1 1872 12250
1876   YES I found bad smells, the bad smells are: 1.Long method, 2.Magic number, 3.Feature envy, 4.Data class, 5.Unclear naming conventions, 6.Redundant code, 7.Missing comments/documentation, 8.Code duplication I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } }
blob Long method, 2Magic number, 3Feature envy,4Data class,5Unclear naming conventions,6Redundant code,7Missing comments/documentation,8Code duplication t f f .Long method, 2.Magic number, 3.Feature envy, 4.Data class, 5.Unclear naming conventions, 6.Redundant code, 7.Missing comments/documentation, 8.Code duplication blob 0 12264 https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 2 1876 12264
286  { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } }
blob long method, data class t t f long method, data class blob 0 3056 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 1 286 3056
2518 {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } }
long method long method, data class t t t  data class   0 14704 https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 1 2518 14704
1879  {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; }
blob blob, data class, long method t t t  data class, long method   0 12276 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 1 1879 12276
1619      { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; }
long method Long Method, Data Class t f t  Data Class   0 11477 https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 1 1619 11477
591 {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { MessageDispatchNotification info = (MessageDispatchNotification)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalLong1(wireFormat, info.getDeliverySequenceId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); return rc + 0; }
feature envy long method, data class t t f long method, data class feature envy 0 5901 https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationMarshaller.java/#L77-L88 1 591 5901
1939 {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static class BuildBinsUDAFEvaluator extends GenericUDAFEvaluator { // PARTIAL1 and COMPLETE private PrimitiveObjectInspector weightOI; // PARTIAL2 and FINAL private StructObjectInspector structOI; private StructField autoShrinkField, histogramField, quantilesField; private BooleanObjectInspector autoShrinkOI; private StandardListObjectInspector histogramOI; private DoubleObjectInspector histogramElOI; private StandardListObjectInspector quantilesOI; private DoubleObjectInspector quantileOI; private int nBGBins = 10000; // # of bins for creating histogram (background bins) private int nBins; // # of bins for result private boolean autoShrink = false; // default: false private double[] quantiles; // for reset @AggregationType(estimable = true) static final class BuildBinsAggregationBuffer extends AbstractAggregationBuffer { boolean autoShrink; NumericHistogram histogram; // histogram used for quantile approximation double[] quantiles; // the quantiles requested BuildBinsAggregationBuffer() {} @Override public int estimate() { return (histogram != null ? histogram.lengthFor() : 0) // histogram + 20 + 8 * (quantiles != null ? quantiles.length : 0) // quantiles + 4; // autoShrink } } @Override public ObjectInspector init(Mode mode, ObjectInspector[] OIs) throws HiveException { super.init(mode, OIs); if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) { weightOI = HiveUtils.asDoubleCompatibleOI(OIs[0]); // set const values nBins = HiveUtils.getConstInt(OIs[1]); if (OIs.length == 3) { autoShrink = HiveUtils.getConstBoolean(OIs[2]); } // check value of `num_of_bins` if (nBins < 2) { throw new UDFArgumentException( "Only greater than or equal to 2 is accepted but " + nBins + " was passed as `num_of_bins`."); } quantiles = getQuantiles(); } else { structOI = (StructObjectInspector) OIs[0]; autoShrinkField = structOI.getStructFieldRef("autoShrink"); histogramField = structOI.getStructFieldRef("histogram"); quantilesField = structOI.getStructFieldRef("quantiles"); autoShrinkOI = (WritableBooleanObjectInspector) autoShrinkField.getFieldObjectInspector(); histogramOI = (StandardListObjectInspector) histogramField.getFieldObjectInspector(); quantilesOI = (StandardListObjectInspector) quantilesField.getFieldObjectInspector(); histogramElOI = (WritableDoubleObjectInspector) histogramOI.getListElementObjectInspector(); quantileOI = (WritableDoubleObjectInspector) quantilesOI.getListElementObjectInspector(); } if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) { final ArrayList fieldOIs = new ArrayList(); fieldOIs.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)); return ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("autoShrink", "histogram", "quantiles"), fieldOIs); } else { return ObjectInspectorFactory.getStandardListObjectInspector( PrimitiveObjectInspectorFactory.writableDoubleObjectInspector); } } private double[] getQuantiles() throws HiveException { final int nQuantiles = nBins - 1; final double[] result = new double[nQuantiles]; for (int i = 0; i < nQuantiles; i++) { result[i] = ((double) (i + 1)) / (nQuantiles + 1); } return result; } @Override public AbstractAggregationBuffer getNewAggregationBuffer() throws HiveException { final BuildBinsAggregationBuffer myAgg = new BuildBinsAggregationBuffer(); myAgg.histogram = new NumericHistogram(); reset(myAgg); return myAgg; } @Override public void reset(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrink; myAgg.histogram.reset(); myAgg.histogram.allocate(nBGBins); myAgg.quantiles = quantiles; } @Override public void iterate(@SuppressWarnings("deprecation") AggregationBuffer agg, Object[] parameters) throws HiveException { Preconditions.checkArgument(parameters.length == 2 || parameters.length == 3); if (parameters[0] == null || parameters[1] == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; // Get and process the current datum myAgg.histogram.add(PrimitiveObjectInspectorUtils.getDouble(parameters[0], weightOI)); } @Override public void merge(@SuppressWarnings("deprecation") AggregationBuffer agg, Object other) throws HiveException { if (other == null) { return; } final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; myAgg.autoShrink = autoShrinkOI.get(structOI.getStructFieldData(other, autoShrinkField)); final List histogram = ((LazyBinaryArray) structOI.getStructFieldData(other, histogramField)).getList(); myAgg.histogram.merge(histogram, histogramElOI); final double[] quantiles = HiveUtils.asDoubleArray( structOI.getStructFieldData(other, quantilesField), quantilesOI, quantileOI); if (quantiles != null && quantiles.length > 0) { myAgg.quantiles = quantiles; } } @Override public Object terminatePartial(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; final Object[] partialResult = new Object[3]; partialResult[0] = new BooleanWritable(myAgg.autoShrink); partialResult[1] = myAgg.histogram.serialize(); partialResult[2] = (myAgg.quantiles != null) ? WritableUtils.toWritableList(myAgg.quantiles) : Collections.singletonList(new DoubleWritable(0)); return partialResult; } @Override public Object terminate(@SuppressWarnings("deprecation") AggregationBuffer agg) throws HiveException { final BuildBinsAggregationBuffer myAgg = (BuildBinsAggregationBuffer) agg; if (myAgg.histogram.getUsedBins() < 1) { // SQL standard - return null for zero elements return null; } else { Preconditions.checkNotNull(myAgg.quantiles); final List result = new ArrayList(); double prev = Double.NEGATIVE_INFINITY; result.add(new DoubleWritable(Double.NEGATIVE_INFINITY)); for (int i = 0; i < myAgg.quantiles.length; i++) { final double val = myAgg.histogram.quantile(myAgg.quantiles[i]); // check duplication if (prev == val) { if (!myAgg.autoShrink) { throw new HiveException( "Quantiles were repeated even though `auto_shrink` is false." + " Reduce `num_of_bins` or enable `auto_shrink`."); } // else: skip duplicated quantile } else { result.add(new DoubleWritable(val)); prev = val; } } result.add(new DoubleWritable(Double.POSITIVE_INFINITY)); return result; } } }
blob data class, long method t t f data class, long method blob 0 12479 https://github.com/apache/incubator-hivemall/blob/37293f64789fbf94d83560374610c1e12db6988c/core/src/main/java/hivemall/ftvec/binning/BuildBinsUDAF.java/#L88-L288 1 1939 12479
898      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class Interleaved { private char[] entries = null; // * private int size = 0; // Number of entries (one entry = length+2 chars) private long entriesGeneratedAtCount = -1; // Keeps track of when the sequential structure was current /** * Ensure that the entries array is in sync with the ngrams. */ public void update() { if (count == entriesGeneratedAtCount) { // Already up to date return; } size = ngrams.size(); final int numChars = (length+2)*size; if (entries == null || entries.length < numChars) { entries = new char[numChars]; } int pos = 0; for (Map.Entry entry: getSortedNgrams()) { for (int l = 0 ; l < length ; l++) { entries[pos + l] = entry.getKey().charAt(l); } entries[pos + length] = (char)(entry.getValue().count / 65536); // Upper 16 bit entries[pos + length + 1] = (char)(entry.getValue().count % 65536); // lower 16 bit pos += length + 2; } entriesGeneratedAtCount = count; } public Entry firstEntry() { Entry entry = new Entry(); if (size > 0) { entry.update(0); } return entry; } private List> getSortedNgrams() { List> entries = new ArrayList>(ngrams.size()); entries.addAll(ngrams.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey().compareTo(o2.getKey()); } }); return entries; } private class Entry implements Comparable { char[] ngram = new char[length]; int count = 0; int pos = 0; private void update(int pos) { this.pos = pos; if (pos >= size) { // Reached the end return; } final int origo = pos*(length+2); System.arraycopy(entries, origo, ngram, 0, length); count = entries[origo+length] * 65536 + entries[origo+length+1]; } @Override public int compareTo(Entry other) { for (int i = 0 ; i < ngram.length ; i++) { if (ngram[i] != other.ngram[i]) { return ngram[i] - other.ngram[i]; } } return 0; } public boolean hasNext() { return pos < size-1; } public boolean hasNgram() { return pos < size; } public void next() { update(pos+1); } public String toString() { return new String(ngram) + "(" + count + ")"; } } }
blob long method, data class t t f long method, data class blob 0 8150 https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/language/LanguageProfile.java/#L224-L311 1 898 8150
1942  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; }
long method long method, data class t t t  data class   0 12499 https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 1 1942 12499
215  {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class FolderArchiveFile implements IArchiveFile { private static final String METEDATA = ".metadata"; private static Logger logger = Logger.getLogger( FolderArchiveFile.class .getName( ) ); protected String folderName; protected String systemId; protected String dependId; private HashSet inputStreams = new HashSet( ); private HashSet outputStreams = new HashSet( ); protected Map properties = new HashMap(); public FolderArchiveFile( String name ) throws IOException { if ( name == null || name.length( ) == 0 ) throw new IOException( CoreMessages .getString( ResourceConstants.FOLDER_NAME_IS_NULL ) ); File file = new File( name ); file.mkdirs( ); this.folderName = file.getCanonicalPath( ); readMetaData( ); } public String getName( ) { return folderName; } private void readMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); if ( file.exists( ) && file.isFile( ) ) { DataInputStream data = new DataInputStream( new FileInputStream( file ) ); try { properties = (Map) IOUtil.readMap( data ); } finally { data.close( ); } } } private void saveMetaData( ) throws IOException { // serialize meta data into .metedata file String meta = ArchiveUtil.getFullPath( folderName, METEDATA ); File file = new File( meta ); DataOutputStream data = new DataOutputStream( new FileOutputStream( file ) ); try { IOUtil.writeMap( data, this.properties ); } finally { data.close( ); } } public void close( ) throws IOException { saveMetaData( ); IOException exception = null; synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { output.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } outputStreams.clear( ); } synchronized ( inputStreams ) { ArrayList inputs = new ArrayList( inputStreams ); for ( RAFolderInputStream input : inputs ) { try { input.close( ); } catch ( IOException ex ) { logger.log( Level.SEVERE, ex.getMessage( ), ex ); if ( exception != null ) { exception = ex; } } } inputStreams.clear( ); } if ( exception != null ) { throw exception; } // ArchiveUtil.archive( folderName, null, fileName ); } public void flush( ) throws IOException { IOException ioex = null; synchronized ( outputStreams ) { for ( RAOutputStream output : outputStreams ) { try { output.flush( ); } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); if ( ioex != null ) { ioex = ex; } } } } if ( ioex != null ) { throw ioex; } } public void refresh( ) throws IOException { } public boolean exists( String name ) { String path = getFilePath( name ); File fd = new File( path ); return fd.exists( ); } public void setCacheSize( long cacheSize ) { } public long getUsedCache( ) { return 0; } public ArchiveEntry openEntry( String name ) throws IOException { String fullPath = getFilePath( name ); File fd = new File( fullPath ); if(fd.exists( )) { return new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); } throw new FileNotFoundException( fullPath ); } public List listEntries( String namePattern ) { ArrayList streamList = new ArrayList( ); String storagePath = getFolderPath( namePattern ); ArrayList files = new ArrayList( ); ArchiveUtil.listAllFiles( new File( storagePath ), files ); for ( File file : files ) { String relativePath = ArchiveUtil.getRelativePath( folderName, file.getPath( ) ); if ( !ArchiveUtil.needSkip( relativePath ) ) { String entryName = ArchiveUtil.getEntryName( folderName, file.getPath( ) ); streamList.add( entryName ); } } return streamList; } public ArchiveEntry createEntry( String name ) throws IOException { String path = getFilePath( name ); File fd = new File( path ); ArchiveUtil.createParentFolder( fd ); FolderArchiveEntry out = new FolderArchiveEntry( name, fd, inputStreams, outputStreams ); return out; } public boolean removeEntry( String name ) throws IOException { String path = getFilePath( name ); try { File fd = new File( path ); return ArchiveUtil.removeFileAndFolder( fd ); } finally { synchronized ( outputStreams ) { ArrayList outputs = new ArrayList( outputStreams ); for ( RAFolderOutputStream output : outputs ) { try { if(name.equals( output.getName( ) )) { output.close( ); } } catch ( IOException ex ) { logger.log(Level.SEVERE, ex.getMessage( ), ex); throw ex; } } } } } public Object lockEntry( String entry ) throws IOException { String path = getFilePath( entry ) + ".lck"; IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); return lockManager.lock( path ); } public void unlockEntry( Object locker ) throws IOException { IArchiveLockManager lockManager = ArchiveLockManager.getInstance( ); lockManager.unlock( locker ); } public String getSystemId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_SYSTEM_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_SYSTEM_ID ) .toString( ); } return null; } public String getDependId( ) { if ( properties.containsKey( ArchiveFileV3.PROPERTY_DEPEND_ID ) ) { return properties.get( ArchiveFileV3.PROPERTY_DEPEND_ID ) .toString( ); } return null; } public void setSystemId(String systemId) { if(systemId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_SYSTEM_ID, systemId ); } } public void setDependId(String dependId) { if(dependId!=null) { this.properties.put( ArchiveFileV3.PROPERTY_DEPEND_ID, dependId ); } } public void save( ) throws IOException { flush(); } public long getLength( ) { long result = 0; List entries = listEntries( null ); for( String entry : entries ) { try { result += openEntry( entry ).getLength( ); } catch ( IOException e ) { e.printStackTrace(); } } return result; } private String getFilePath( String entryName ) { return ArchiveUtil.getFilePath( folderName, entryName ); } private String getFolderPath( String entryName ) { return ArchiveUtil.getFolderPath( folderName, entryName ); } }
blob data class t t f data class blob 0 2326 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/FolderArchiveFile.java/#L27-L359 1 215 2326
2039 { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } }
blob long method, data class t t f long method, data class blob 0 12844 https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 1 2039 12844
2690 {"response":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } }
blob data class, long method t t f data class, long method blob 0 15292 https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 1 2690 15292
1546 {"result": "YES I found bad smells", "bad smells are": ["2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Service ("knownRepositoryContentConsumer#create-archiva-metadata") @Scope ("prototype") public class ArchivaMetadataCreationConsumer extends AbstractMonitoredConsumer implements KnownRepositoryContentConsumer, RegistryListener { private String id = "create-archiva-metadata"; private String description = "Create basic metadata for Archiva to be able to reference the artifact"; @Inject private ArchivaConfiguration configuration; @Inject private FileTypes filetypes; private Date whenGathered; private List includes = new ArrayList<>( 0 ); /** * FIXME: this could be multiple implementations and needs to be configured. */ @Inject private RepositorySessionFactory repositorySessionFactory; /** * FIXME: this needs to be configurable based on storage type - and could also be instantiated per repo. Change to a * factory. */ @Inject @Named (value = "repositoryStorage#maven2") private RepositoryStorage repositoryStorage; private static final Logger log = LoggerFactory.getLogger( ArchivaMetadataCreationConsumer.class ); private String repoId; @Override public String getId() { return this.id; } @Override public String getDescription() { return this.description; } @Override public List getExcludes() { return getDefaultArtifactExclusions(); } @Override public List getIncludes() { return this.includes; } @Override public void beginScan( ManagedRepository repo, Date whenGathered ) throws ConsumerException { repoId = repo.getId(); this.whenGathered = whenGathered; } @Override public void beginScan( ManagedRepository repository, Date whenGathered, boolean executeOnEntireRepo ) throws ConsumerException { beginScan( repository, whenGathered ); } @Override public void processFile( String path ) throws ConsumerException { RepositorySession repositorySession = repositorySessionFactory.createSession(); try { // note that we do minimal processing including checksums and POM information for performance of // the initial scan. Any request for this information will be intercepted and populated on-demand // or picked up by subsequent scans ArtifactMetadata artifact = repositoryStorage.readArtifactMetadataFromPath( repoId, path ); ProjectMetadata project = new ProjectMetadata(); project.setNamespace( artifact.getNamespace() ); project.setId( artifact.getProject() ); String projectVersion = VersionUtil.getBaseVersion( artifact.getVersion() ); MetadataRepository metadataRepository = repositorySession.getRepository(); boolean createVersionMetadata = false; // FIXME: maybe not too efficient since it may have already been read and stored for this artifact ProjectVersionMetadata versionMetadata = null; try { ReadMetadataRequest readMetadataRequest = new ReadMetadataRequest().repositoryId( repoId ).namespace( artifact.getNamespace() ).projectId( artifact.getProject() ).projectVersion( projectVersion ); versionMetadata = repositoryStorage.readProjectVersionMetadata( readMetadataRequest ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataNotFoundException e ) { log.warn( "Missing or invalid POM for artifact:{} (repository:{}); creating empty metadata", path, repoId ); versionMetadata = new ProjectVersionMetadata(); versionMetadata.setId( projectVersion ); versionMetadata.setIncomplete( true ); createVersionMetadata = true; } catch ( RepositoryStorageMetadataInvalidException e ) { log.warn( "Error occurred resolving POM for artifact:{} (repository:{}); message: {}", new Object[]{ path, repoId, e.getMessage() } ); } // read the metadata and update it if it is newer or doesn't exist artifact.setWhenGathered( whenGathered ); metadataRepository.updateArtifact( repoId, project.getNamespace(), project.getId(), projectVersion, artifact ); if ( createVersionMetadata ) { metadataRepository.updateProjectVersion( repoId, project.getNamespace(), project.getId(), versionMetadata ); } metadataRepository.updateProject( repoId, project ); repositorySession.save(); } catch ( MetadataRepositoryException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}" , path, repoId, e.getMessage(), e ); repositorySession.revert(); } catch ( RepositoryStorageRuntimeException e ) { log.warn( "Error occurred persisting metadata for artifact:{} (repository:{}); message: {}", path, repoId, e.getMessage(), e ); repositorySession.revert(); } finally { repositorySession.close(); } } @Override public void processFile( String path, boolean executeOnEntireRepo ) throws ConsumerException { processFile( path ); } @Override public void completeScan() { /* do nothing */ } @Override public void completeScan( boolean executeOnEntireRepo ) { completeScan(); } @Override public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { if ( ConfigurationNames.isRepositoryScanning( propertyName ) ) { initIncludes(); } } @Override public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue ) { /* do nothing */ } private void initIncludes() { includes = new ArrayList( filetypes.getFileTypePatterns( FileTypes.ARTIFACTS ) ); } @PostConstruct public void initialize() { configuration.addChangeListener( this ); initIncludes(); } }
blob 2 Data Class t f f 2. Data Class blob 0 11252 https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-consumers/archiva-metadata-consumer/src/main/java/org/apache/archiva/consumers/metadata/ArchivaMetadataCreationConsumer.java/#L59-L264 1 1546 11252
1462  YES, I found bad smells: 1. Long method 2. Feature envy 3. Primitive obsession 4. Data class 5. Poor encapsulation 6. Redundant fields 7. Duplicate code and functionality in methods 8. Inconsistent variable naming 9. Lack of comments and documentation 10. Poor naming conventions for methods and variables I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } }
blob  Long method2 Feature envy3 Primitive obsession4 Data class5 Poor encapsulation6 Redundant fields7 Duplicate code and functionality in methods8 Inconsistent variable naming9 Lack of comments and documentation t f f . Long method2. Feature envy3. Primitive obsession4. Data class5. Poor encapsulation6. Redundant fields7. Duplicate code and functionality in methods8. Inconsistent variable naming9. Lack of comments and documentation blob 0 11026 https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 2 1462 11026
2479 {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } }
blob long method, data class t t f long method, data class blob 0 14592 https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 1 2479 14592
252  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@PublicEvolving public class ByteValueParser extends FieldParser { private ByteValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, ByteValue reusable) { if (startPos == limit) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } int val = 0; boolean neg = false; this.result = reusable; final int delimLimit = limit - delimiter.length + 1; if (bytes[startPos] == '-') { neg = true; startPos++; // check for empty field with only the sign if (startPos == limit || (startPos < delimLimit && delimiterNext(bytes, startPos, delimiter))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ORPHAN_SIGN); return -1; } } for (int i = startPos; i < limit; i++) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { if (i == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } reusable.setValue((byte) (neg ? -val : val)); return i + delimiter.length; } if (bytes[i] < 48 || bytes[i] > 57) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } val *= 10; val += bytes[i] - 48; if (val > Byte.MAX_VALUE && (!neg || val > -Byte.MIN_VALUE)) { setErrorState(ParseErrorState.NUMERIC_VALUE_OVERFLOW_UNDERFLOW); return -1; } } reusable.setValue((byte) (neg ? -val : val)); return limit; } @Override public ByteValue createValue() { return new ByteValue(); } @Override public ByteValue getLastResult() { return this.result; } }
blob long method, data class t t f long method, data class blob 0 2712 https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/types/parser/ByteValueParser.java/#L29-L96 1 252 2712
1066 {"message": "YES I found bad smells the bad smells are: 1. Data class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } }
blob 1. data class t t f 1. data class blob 0 9581 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 1 1066 9581
1274 {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 10582 https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 1 1274 10582
3618    {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface JsonObjectMapper { default String toJson(Object value) throws IOException { return null; } default void toJson(Object value, Writer writer) throws IOException { } default N toJsonNode(Object value) throws IOException { return null; } default T fromJson(Object json, Class valueType) throws IOException { return null; } /** * Deserialize a JSON to an expected {@link ResolvableType}. * @param json the JSON to deserialize * @param valueType the {@link ResolvableType} for the target object. * @param the expected object type * @return deserialization result object * @throws IOException a JSON parsing exception * @since 5.2 */ default T fromJson(Object json, ResolvableType valueType) throws IOException { return null; } default T fromJson(Object json, Map javaTypes) throws IOException { return null; } default T fromJson(P parser, Type valueType) throws IOException { return null; } default void populateJavaTypes(Map map, Object object) { Class targetClass = object.getClass(); Class contentClass = null; Class keyClass = null; map.put(JsonHeaders.TYPE_ID, targetClass); if (object instanceof Collection && !((Collection) object).isEmpty()) { Object firstElement = ((Collection) object).iterator().next(); if (firstElement != null) { contentClass = firstElement.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } } if (object instanceof Map && !((Map) object).isEmpty()) { Object firstValue = ((Map) object).values().iterator().next(); if (firstValue != null) { contentClass = firstValue.getClass(); map.put(JsonHeaders.CONTENT_TYPE_ID, contentClass); } Object firstKey = ((Map) object).keySet().iterator().next(); if (firstKey != null) { keyClass = firstKey.getClass(); map.put(JsonHeaders.KEY_TYPE_ID, keyClass); } } map.put(JsonHeaders.RESOLVABLE_TYPE, buildResolvableType(targetClass, contentClass, keyClass)); } static ResolvableType buildResolvableType(Class targetClass, @Nullable Class contentClass, @Nullable Class keyClass) { if (keyClass != null) { return TypeDescriptor .map(targetClass, TypeDescriptor.valueOf(keyClass), TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else if (contentClass != null) { return TypeDescriptor .collection(targetClass, TypeDescriptor.valueOf(contentClass)) .getResolvableType(); } else { return ResolvableType.forClass(targetClass); } } }
blob data class t t f data class blob 0 8109 https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-core/src/main/java/org/springframework/integration/support/json/JsonObjectMapper.java/#L41-L130 1 3618 8109
166 {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings({"rawtypes", "unchecked"}) public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler { protected final JMXAgentContext agentContext; protected StandardMBean mbean; protected final AtomicLong trackedId = new AtomicLong(); /** * * @param agentContext * @param filter */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) { super(agentContext.getBundleContext(), filter, null); this.agentContext = agentContext; } /** * * @param agentContext * @param clazz */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) { super(agentContext.getBundleContext(), clazz, null); this.agentContext = agentContext; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Logger logger = agentContext.getLogger(); Object trackedService = null; long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); //API stipulates versions for compendium services with static ObjectName //This shouldn't happen but added as a consistency check if (trackedId.compareAndSet(0, serviceId)) { logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceId + "]"); trackedService = context.getService(reference); mbean = constructInjectMBean(trackedService); agentContext.registerMBean(AbstractCompendiumHandler.this); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed"); } return trackedService; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { Logger logger = agentContext.getLogger(); long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID); if (trackedId.compareAndSet(serviceID, 0)) { logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceID + "]"); agentContext.unregisterMBean(AbstractCompendiumHandler.this); context.ungetService(reference); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed"); } } private String getServiceDescription(ServiceReference reference) { String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION); if (serviceDescription == null) { Object obj = reference.getProperty(Constants.OBJECTCLASS); if (obj instanceof String[]) { StringBuilder sb = new StringBuilder(); for (String s : (String[]) obj) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } serviceDescription = sb.toString(); } else { serviceDescription = obj.toString(); } } return serviceDescription; } /** * Gets the StandardMBean managed by this handler when the backing service is available or null * * @see org.apache.aries.jmx.MBeanHandler#getMbean() */ public StandardMBean getMbean() { return mbean; } /** * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied * service tracked by this handler * * @param targetService * the compendium service tracked by this handler * @return The StandardMBean instance whose registration lifecycle will be managed by this handler */ protected abstract StandardMBean constructInjectMBean(Object targetService); /** * The base name of the MBean. Will be expanded with the framework name and the UUID. * @return */ protected abstract String getBaseName(); /** * @see org.apache.aries.jmx.MBeanHandler#getName() */ public String getName() { return ObjectNameUtils.createFullObjectName(context, getBaseName()); } }
blob data class t t f data class blob 0 2010 https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java/#L43-L166 1 166 2010
1445 {"result": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } }
blob blob, data class t t t  data class   0 10981 https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 1 1445 10981
1924  { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } }
blob long method, data class t t f long method, data class blob 0 12432 https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 1 1924 12432
722    { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } }
long method long method, data class t t t  data class   0 6833 https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 1 722 6833
1390    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } }
long method Long Method, Data Class t f t  Data Class   0 10841 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 1 1390 10841
1200      { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; }
long method 1. long method, 2. data class t t t  2. data class   0 10279 https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 1 1200 10279
210  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } }
blob data class, long method t t f data class, long method blob 0 2313 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 1 210 2313
49 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ActorAddFeature extends AbstractAddShapeFeature { private final static Logger LOGGER = LoggerFactory.getLogger(ActorAddFeature.class); public ActorAddFeature(IFeatureProvider fp) { super(fp); } /** * Extends Graphiti's default linking between a pictogram element and a business object, * by also storing extra properties to facilitate determining changes between business model and graphical model. * * @param pe * @param businessObject * @param categories */ protected void link(IContext context, PictogramElement pe, Object businessObject, Category... categories) { super.link(pe, businessObject); // add property on the graphical model element, identifying the associated triq model element // so we can easily distinguish and identify them later on for updates etc for (Category category : categories) { category.storeIn(pe); } if (businessObject instanceof NamedObj) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_NAME, ((NamedObj) businessObject).getName()); String iconResource = (String) context.getProperty("icon"); if(iconResource!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON, iconResource); } String iconType = (String) context.getProperty("iconType"); if(iconType!=null) { Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.ICON_TYPE, iconType); } } Graphiti.getPeService().setPropertyValue(pe, FeatureConstants.BO_CLASS, businessObject.getClass().getName()); } @Override public boolean canAdd(IAddContext context) { // check if user wants to add an actor return (context.getNewObject() instanceof Actor); } @Override public PictogramElement add(IAddContext context) { Entity addedActor = (Entity) context.getNewObject(); ContainerShape targetContainer = context.getTargetContainer(); // This should be a duplicate from what's in ModelElementCreateFeature, // to link the toplevel CompositeActor to the Diagram. // So let's try to do without this. // Object topLevelForDiagram = getBusinessObjectForPictogramElement(getDiagram()); // if (topLevelForDiagram == null) { // link(getDiagram(), addedActor.getContainer()); // } int xLocation = context.getX(); int yLocation = context.getY(); IPeCreateService peCreateService = Graphiti.getPeCreateService(); IGaService gaService = Graphiti.getGaService(); ContainerShape containerShape = peCreateService.createContainerShape(targetContainer, true); link(context, containerShape, addedActor, BoCategory.Actor); GraphicsAlgorithm invisibleRectangle = null; invisibleRectangle = gaService.createInvisibleRectangle(containerShape); GraphicsAlgorithm actorShapeGA = null; String iconResource = (String) context.getProperty("icon"); String iconType = (String) context.getProperty("iconType"); switch (iconType) { case TriqFeatureProvider.ICONTYPE_SVG: case TriqFeatureProvider.ICONTYPE_PTOLEMY: actorShapeGA = buildExternallyDefinedShape(context, gaService, invisibleRectangle, containerShape, iconType, iconResource); break; default: actorShapeGA = buildDefaultShape(context, gaService, invisibleRectangle, containerShape, addedActor, iconResource); } int width = actorShapeGA.getWidth(); int height = actorShapeGA.getHeight(); gaService.setLocationAndSize(invisibleRectangle, xLocation, yLocation, width + 2*ACTOR_X_MARGIN, height + 2*ACTOR_Y_MARGIN); // SHAPES FOR PORTS; added both on default shapes and on custom/externally-defined icons (SVG, ptolemy icons) Map> categorizedPorts = addedActor.getPorts().stream().collect(groupingBy(Port::getDirection, mapping(Function.identity(), toList()))); categorizedPorts.forEach((direction, ports) -> createAnchorsAndPortShapesForDirection(context, containerShape, direction, ports)); layoutPictogramElement(containerShape); return containerShape; } /** * Builds the default actor shape, consisting of a rounded rectangle containing a small icon and the actor's name. * * Used when no specific image/icon definition has been set for a given actor. * * @param gaService * @param invisibleRectangle * @param containerShape * @param addedActor * @param iconResource * @return */ protected GraphicsAlgorithm buildDefaultShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, Entity addedActor, String iconResource) { IPeCreateService peCreateService = Graphiti.getPeCreateService(); int width = ACTOR_VISIBLE_WIDTH; int height = ACTOR_VISIBLE_HEIGHT; // create and set graphics algorithm RoundedRectangle actorShapeGA = gaService.createRoundedRectangle(invisibleRectangle, 5, 5); actorShapeGA.setForeground(manageColor(ACTOR_FOREGROUND)); actorShapeGA.setBackground(manageColor(ACTOR_BACKGROUND)); actorShapeGA.setLineWidth(2); gaService.setLocationAndSize(actorShapeGA, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, width, height); // add the actor's icon if (!StringUtils.isBlank(iconResource)) { try { final Shape shape = peCreateService.createShape(containerShape, false); final Image image = gaService.createImage(shape, iconResource); addedActor.setIconId(iconResource); gaService.setLocationAndSize(image, ACTOR_ICON_X_MARGIN, ACTOR_ICON_Y_MARGIN, ACTOR_ICON_SIZE, ACTOR_ICON_SIZE); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } catch (Exception e) { LOGGER.error(ErrorCode.MODEL_CONFIGURATION_ERROR + " - Error trying to add actor icon for " + addedActor, e); } } // SHAPE WITH LINE { // create shape for line Shape shape = peCreateService.createShape(containerShape, false); // create and set graphics algorithm Polyline polyline = gaService.createPolyline(shape, ACTOR_TEXT_UNDERLINE_SHAPE); polyline.setForeground(manageColor(ACTOR_FOREGROUND)); polyline.setLineWidth(2); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); } // SHAPE WITH actor name as TEXT { // create shape for text Shape shape = peCreateService.createShape(containerShape, false); // create and set text graphics algorithm Text text = gaService.createText(shape, addedActor.getName()); text.setForeground(manageColor(ACTOR_NAME_FOREGROUND)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); // vertical alignment has as default value "center" text.setFont(gaService.manageDefaultFont(getDiagram(), false, true)); gaService.setLocationAndSize(text, ACTOR_TEXT_X_MARGIN, ACTOR_Y_MARGIN, ACTOR_TEXT_WIDTH, ACTOR_TEXT_HEIGHT); // create link and wire it link(context, shape, addedActor, BoCategory.Actor); // provide information to support direct-editing directly // after object creation (must be activated additionally) IDirectEditingInfo directEditingInfo = getFeatureProvider().getDirectEditingInfo(); // set container shape for direct editing after object creation directEditingInfo.setMainPictogramElement(containerShape); // set shape and graphics algorithm where the editor for // direct editing shall be opened after object creation directEditingInfo.setPictogramElement(shape); directEditingInfo.setGraphicsAlgorithm(text); } return actorShapeGA; } /** * Builds the actor shape based on an external definition, e.g. in SVG or in Ptolemy icon moml files. * * @param gaService * @param invisibleRectangle * @param containerShape * @param iconType * @param iconResource * @return */ protected GraphicsAlgorithm buildExternallyDefinedShape(IAddContext context, IGaService gaService, GraphicsAlgorithm invisibleRectangle, ContainerShape containerShape, String iconType, String iconResource) { GraphicsAlgorithm extFigure = Graphiti.getGaCreateService().createPlatformGraphicsAlgorithm(invisibleRectangle, iconType); { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconType"); property.setValue(iconType); extFigure.getProperties().add(property); } { Property property = MmFactory.eINSTANCE.createProperty(); property.setKey("iconResource"); property.setValue(iconResource); extFigure.getProperties().add(property); } gaService.setLocationAndSize(extFigure, ACTOR_X_MARGIN, ACTOR_Y_MARGIN, 40, 40); return extFigure; } /** * * @param context * @param containerShape * @param direction * @param portList */ private void createAnchorsAndPortShapesForDirection(IAddContext context, ContainerShape containerShape, Direction direction, List portList) { Map anchorMap = (Map) context.getProperty(FeatureConstants.ANCHORMAP_NAME); // The list should only contain pairs for which there are still ports on the actor. // But there may still be new ports for which no anchor is present yet in the graphical model. int portCount = portList.size(); for (int i = 0; i < portCount; ++i) { Port p = portList.get(i); Anchor anchor = PortShapes.createAnchor(containerShape, direction, p, i, portCount); PortShapes.createPortShape(getDiagram(), anchor, direction, p); link(context, anchor, p, BoCategory.Port, PortCategory.valueOf(direction)); if (anchorMap != null) { anchorMap.put(p.getFullName(), anchor); } } } }
blob long method, data class t t f long method, data class blob 0 856 https://github.com/eclipse/triquetrum/blob/e4c5834ce3d68bd97820157d426a427dfe8e2a9b/plugins/editor/org.eclipse.triquetrum.workflow.editor/src/main/java/org/eclipse/triquetrum/workflow/editor/features/ActorAddFeature.java/#L57-L288 1 49 856
28 { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
long method data class, long method t t t data class   0 712 https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 1 28 712
1392 {"response": "YES I found bad smells", "detected_bad_smells": ["2. Long Method", "3. Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class BDMVSAXHandler extends DefaultHandler { private String current_tag; private StringBuffer buff = new StringBuffer(); private boolean insideTitle; private boolean insideDescription; private int maxThumbSize = -1; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("di:title".equalsIgnoreCase(qName)) { insideTitle = true; } else if ("di:description".equalsIgnoreCase(qName)) { insideDescription = true; } else if (insideDescription && "di:thumbnail".equals(qName)) { String thumbStr = attributes.getValue("href"); String sizeStr = attributes.getValue("size"); if (thumbStr != null && sizeStr != null) { int xidx = sizeStr.indexOf('x'); if (xidx != -1) { int currSize = 0; try { currSize = Integer.parseInt(sizeStr.substring(0, xidx)) * Integer.parseInt(sizeStr.substring(xidx + 1)); } catch (NumberFormatException nfe) { if (sage.Sage.DBG) System.out.println("ERROR could not extract BDMV thumbnail size of :" + nfe + " from " + sizeStr); } if (currSize > maxThumbSize) { metaThumbnail = new java.io.File(new java.io.File(bdmvDir, "META" + java.io.File.separator + "DL"), thumbStr).getAbsolutePath(); } } } } current_tag = qName; } public void characters(char[] ch, int start, int length) { String data = new String(ch,start,length); //Jump blank chunk if (data.trim().length() == 0) return; buff.append(data); } public void endElement(String uri, String localName, String qName) { String data = buff.toString().trim(); if (qName.equals(current_tag)) buff = new StringBuffer(); if ("di:title".equals(qName)) insideTitle = false; else if ("di:description".equals(qName)) insideDescription = false; else if (insideTitle && "di:name".equals(qName)) { metaTitle = data; } } }
blob 2. long method, 3. data class t t f 2. long method, 3. data class blob 0 10844 https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/media/bluray/BluRayParser.java/#L372-L440 1 1392 10844
2062      { "message": "YES I found bad smells", "bad smells are": "2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); }
long method 2. data class t t f 2. data class long method 0 12975 https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 1 2062 12975
1990 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ModelDataGenerator { private static final Logger logger = LoggerFactory.getLogger(ModelDataGenerator.class); final private DataModelDesc model; final private int targetRows; final private ResourceStore outputStore; final private String outputPath; boolean outprint = false; // for debug public ModelDataGenerator(DataModelDesc model, int nRows) { this(model, nRows, ResourceStore.getStore(model.getConfig())); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore) { this(model, nRows, outputStore, "/data"); } private ModelDataGenerator(DataModelDesc model, int nRows, ResourceStore outputStore, String outputPath) { this.model = model; this.targetRows = nRows; this.outputStore = outputStore; this.outputPath = outputPath; } public void generate() throws IOException { Set generated = new HashSet<>(); Set allTableDesc = new LinkedHashSet<>(); JoinTableDesc[] allTables = model.getJoinTables(); for (int i = allTables.length - 1; i >= -1; i--) { // reverse order needed for FK generation TableDesc table = (i == -1) ? model.getRootFactTable().getTableDesc() : allTables[i].getTableRef().getTableDesc(); allTableDesc.add(table); if (generated.contains(table)) continue; logger.info(String.format(Locale.ROOT, "generating data for %s", table)); boolean gen = generateTable(table); if (gen) generated.add(table); } generateDDL(allTableDesc); } private boolean generateTable(TableDesc table) throws IOException { TableGenConfig config = new TableGenConfig(table, this); if (!config.needGen) return false; ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateTableInternal(table, config, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(table)); return true; } private void generateTableInternal(TableDesc table, TableGenConfig config, PrintWriter out) throws IOException { ColumnDesc[] columns = table.getColumns(); ColumnGenerator[] colGens = new ColumnGenerator[columns.length]; Iterator[] colIters = new Iterator[columns.length]; // config.rows is either a multiplier (0,1] or an absolute row number int tableRows = (int) ((config.rows > 1) ? config.rows : targetRows * config.rows); tableRows = Math.max(1, tableRows); // same seed for all columns, to ensure composite FK columns generate correct pairs long seed = System.currentTimeMillis(); for (int i = 0; i < columns.length; i++) { colGens[i] = new ColumnGenerator(columns[i], tableRows, this); colIters[i] = colGens[i].generate(seed); } for (int i = 0; i < tableRows; i++) { for (int c = 0; c < columns.length; c++) { if (c > 0) out.print(","); String v = colIters[c].next(); Preconditions.checkState(v == null || !v.contains(",")); out.print(v); } out.print("\n"); } } private void generateDDL(Set tables) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter pout = new PrintWriter(new OutputStreamWriter(bout, StandardCharsets.UTF_8)); generateDatabaseDDL(tables, pout); generateCreateTableDDL(tables, pout); generateLoadDataDDL(tables, pout); pout.close(); bout.close(); saveResource(bout.toByteArray(), path(model)); } private void generateDatabaseDDL(Set tables, PrintWriter out) { Set dbs = new HashSet<>(); for (TableDesc t : tables) { String db = t.getDatabase(); if (StringUtils.isBlank(db) == false && "DEFAULT".equals(db) == false) dbs.add(db); } for (String db : dbs) { out.print("CREATE DATABASE IF NOT EXISTS " + normHiveIdentifier(db) + ";\n"); } out.print("\n"); } private void generateCreateTableDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) continue; out.print("DROP TABLE IF EXISTS " + normHiveIdentifier(t.getIdentity()) + ";\n"); out.print("CREATE TABLE " + normHiveIdentifier(t.getIdentity()) + "(" + "\n"); for (int i = 0; i < t.getColumns().length; i++) { ColumnDesc col = t.getColumns()[i]; out.print(" "); if (i > 0) { out.print(","); } out.print(normHiveIdentifier(col.getName()) + " " + hiveType(col.getType()) + "\n"); } out.print(")" + "\n"); out.print("ROW FORMAT DELIMITED FIELDS TERMINATED BY ','" + "\n"); out.print("STORED AS TEXTFILE" + ";\n"); out.print("\n"); } } private String normHiveIdentifier(String orig) { return "`" + orig + "`"; } private String hiveType(DataType type) { String t = type.toString(); if (t.startsWith("varchar")) return "string"; else if (t.startsWith("integer")) return "int"; else return t; } private void generateLoadDataDDL(Set tables, PrintWriter out) { for (TableDesc t : tables) { if (t.isView()) { out.print("-- " + t.getIdentity() + " is view \n"); continue; } out.print("LOAD DATA LOCAL INPATH '" + t.getIdentity() + ".csv' OVERWRITE INTO TABLE " + normHiveIdentifier(t.getIdentity()) + ";\n"); } } public boolean existsInStore(TableDesc table) throws IOException { return outputStore.exists(path(table)); } public boolean isPK(ColumnDesc col) { for (JoinTableDesc joinTable : model.getJoinTables()) { JoinDesc join = joinTable.getJoin(); for (TblColRef pk : join.getPrimaryKeyColumns()) { if (pk.getColumnDesc().equals(col)) return true; } } return false; } public List getPkValuesIfIsFk(ColumnDesc fk) throws IOException { JoinTableDesc[] joinTables = model.getJoinTables(); for (int i = 0; i < joinTables.length; i++) { JoinTableDesc joinTable = joinTables[i]; ColumnDesc pk = findPk(joinTable, fk); if (pk == null) continue; List pkValues = getPkValues(pk); if (pkValues != null) return pkValues; } return null; } private ColumnDesc findPk(JoinTableDesc joinTable, ColumnDesc fk) { TblColRef[] fkCols = joinTable.getJoin().getForeignKeyColumns(); for (int i = 0; i < fkCols.length; i++) { if (fkCols[i].getColumnDesc().equals(fk)) return joinTable.getJoin().getPrimaryKeyColumns()[i].getColumnDesc(); } return null; } public List getPkValues(ColumnDesc pk) throws IOException { if (existsInStore(pk.getTable()) == false) return null; List r = new ArrayList<>(); BufferedReader in = new BufferedReader( new InputStreamReader(outputStore.getResource(path(pk.getTable())).content(), "UTF-8")); try { String line; while ((line = in.readLine()) != null) { r.add(line.split(",")[pk.getZeroBasedIndex()]); } } finally { IOUtils.closeQuietly(in); } return r; } private void saveResource(byte[] content, String path) throws IOException { System.out.println("Generated " + outputStore.getReadableResourcePath(path)); if (outprint) { System.out.println(Bytes.toString(content)); } outputStore.putResource(path, new ByteArrayInputStream(content), System.currentTimeMillis()); } private String path(TableDesc table) { return outputPath + "/" + table.getIdentity() + ".csv"; } private String path(DataModelDesc model) { return outputPath + "/" + "ddl_" + model.getName() + ".sql"; } public DataModelDesc getModle() { return model; } public static void main(String[] args) throws IOException { String modelName = args[0]; int nRows = Integer.parseInt(args[1]); String outputDir = args.length > 2 ? args[2] : null; KylinConfig conf = KylinConfig.getInstanceFromEnv(); DataModelDesc model = DataModelManager.getInstance(conf).getDataModelDesc(modelName); ResourceStore store = outputDir == null ? ResourceStore.getStore(conf) : ResourceStore.getStore(mockup(outputDir)); ModelDataGenerator gen = new ModelDataGenerator(model, nRows, store); gen.generate(); } private static KylinConfig mockup(String outputDir) { KylinConfig mockup = KylinConfig.createKylinConfig(KylinConfig.getInstanceFromEnv()); mockup.setMetadataUrl(new File(outputDir).getAbsolutePath()); return mockup; } }
blob long method, data class t t f long method, data class blob 0 12680 https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-metadata/src/main/java/org/apache/kylin/source/datagen/ModelDataGenerator.java/#L56-L328 1 1990 12680
392 {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } }
blob long method, data class t t f long method, data class blob 0 3965 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 1 392 3965
848 { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class PolylineConnection extends Polyline implements Connection, AnchorListener { private ConnectionAnchor startAnchor, endAnchor; private ConnectionRouter connectionRouter = ConnectionRouter.NULL; private RotatableDecoration startArrow, endArrow; { setLayoutManager(new DelegatingLayout()); addPoint(new Point(0, 0)); addPoint(new Point(100, 100)); } /** * Hooks the source and target anchors. * * @see Figure#addNotify() */ public void addNotify() { super.addNotify(); hookSourceAnchor(); hookTargetAnchor(); } /** * Appends the given routing listener to the list of listeners. * * @param listener * the routing listener * @since 3.2 */ public void addRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.add(listener); } else connectionRouter = new RoutingNotifier(connectionRouter, listener); } /** * Called by the anchors of this connection when they have moved, * revalidating this polyline connection. * * @param anchor * the anchor that moved */ public void anchorMoved(ConnectionAnchor anchor) { revalidate(); } /** * Returns the bounds which holds all the points in this polyline * connection. Returns any previously existing bounds, else calculates by * unioning all the children's dimensions. * * @return the bounds */ public Rectangle getBounds() { if (bounds == null) { super.getBounds(); for (int i = 0; i < getChildren().size(); i++) { IFigure child = (IFigure) getChildren().get(i); bounds.union(child.getBounds()); } } return bounds; } /** * Returns the ConnectionRouter used to layout this connection. * Will not return null. * * @return this connection's router */ public ConnectionRouter getConnectionRouter() { if (connectionRouter instanceof RoutingNotifier) return ((RoutingNotifier) connectionRouter).realRouter; return connectionRouter; } /** * Returns this connection's routing constraint from its connection router. * May return null. * * @return the connection's routing constraint */ public Object getRoutingConstraint() { if (getConnectionRouter() != null) return getConnectionRouter().getConstraint(this); else return null; } /** * @return the anchor at the start of this polyline connection (may be null) */ public ConnectionAnchor getSourceAnchor() { return startAnchor; } /** * @return the source decoration (may be null) */ protected RotatableDecoration getSourceDecoration() { return startArrow; } /** * @return the anchor at the end of this polyline connection (may be null) */ public ConnectionAnchor getTargetAnchor() { return endAnchor; } /** * @return the target decoration (may be null) * * @since 2.0 */ protected RotatableDecoration getTargetDecoration() { return endArrow; } private void hookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().addAnchorListener(this); } private void hookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().addAnchorListener(this); } /** * Layouts this polyline. If the start and end anchors are present, the * connection router is used to route this, after which it is laid out. It * also fires a moved method. */ public void layout() { if (getSourceAnchor() != null && getTargetAnchor() != null) connectionRouter.route(this); Rectangle oldBounds = bounds; super.layout(); bounds = null; if (!getBounds().contains(oldBounds)) { getParent().translateToParent(oldBounds); getUpdateManager().addDirtyRegion(getParent(), oldBounds); } repaint(); fireFigureMoved(); } /** * Called just before the receiver is being removed from its parent. Results * in removing itself from the connection router. * * @since 2.0 */ public void removeNotify() { unhookSourceAnchor(); unhookTargetAnchor(); connectionRouter.remove(this); super.removeNotify(); } /** * Removes the first occurence of the given listener. * * @param listener * the listener being removed * @since 3.2 */ public void removeRoutingListener(RoutingListener listener) { if (connectionRouter instanceof RoutingNotifier) { RoutingNotifier notifier = (RoutingNotifier) connectionRouter; notifier.listeners.remove(listener); if (notifier.listeners.isEmpty()) connectionRouter = notifier.realRouter; } } /** * @see IFigure#revalidate() */ public void revalidate() { super.revalidate(); connectionRouter.invalidate(this); } /** * Sets the connection router which handles the layout of this polyline. * Generally set by the parent handling the polyline connection. * * @param cr * the connection router */ public void setConnectionRouter(ConnectionRouter cr) { if (cr == null) cr = ConnectionRouter.NULL; ConnectionRouter oldRouter = getConnectionRouter(); if (oldRouter != cr) { connectionRouter.remove(this); if (connectionRouter instanceof RoutingNotifier) ((RoutingNotifier) connectionRouter).realRouter = cr; else connectionRouter = cr; firePropertyChange(Connection.PROPERTY_CONNECTION_ROUTER, oldRouter, cr); revalidate(); } } /** * Sets the routing constraint for this connection. * * @param cons * the constraint */ public void setRoutingConstraint(Object cons) { if (connectionRouter != null) connectionRouter.setConstraint(this, cons); revalidate(); } /** * Sets the anchor to be used at the start of this polyline connection. * * @param anchor * the new source anchor */ public void setSourceAnchor(ConnectionAnchor anchor) { if (anchor == startAnchor) return; unhookSourceAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); startAnchor = anchor; if (getParent() != null) hookSourceAnchor(); revalidate(); } /** * Sets the decoration to be used at the start of the {@link Connection}. * * @param dec * the new source decoration * @since 2.0 */ public void setSourceDecoration(RotatableDecoration dec) { if (startArrow == dec) return; if (startArrow != null) remove(startArrow); startArrow = dec; if (startArrow != null) add(startArrow, new ArrowLocator(this, ConnectionLocator.SOURCE)); } /** * Sets the anchor to be used at the end of the polyline connection. Removes * this listener from the old anchor and adds it to the new anchor. * * @param anchor * the new target anchor */ public void setTargetAnchor(ConnectionAnchor anchor) { if (anchor == endAnchor) return; unhookTargetAnchor(); // No longer needed, revalidate does this. // getConnectionRouter().invalidate(this); endAnchor = anchor; if (getParent() != null) hookTargetAnchor(); revalidate(); } /** * Sets the decoration to be used at the end of the {@link Connection}. * * @param dec * the new target decoration */ public void setTargetDecoration(RotatableDecoration dec) { if (endArrow == dec) return; if (endArrow != null) remove(endArrow); endArrow = dec; if (endArrow != null) add(endArrow, new ArrowLocator(this, ConnectionLocator.TARGET)); } private void unhookSourceAnchor() { if (getSourceAnchor() != null) getSourceAnchor().removeAnchorListener(this); } private void unhookTargetAnchor() { if (getTargetAnchor() != null) getTargetAnchor().removeAnchorListener(this); } final class RoutingNotifier implements ConnectionRouter { ConnectionRouter realRouter; List listeners = new ArrayList(1); RoutingNotifier(ConnectionRouter router, RoutingListener listener) { realRouter = router; listeners.add(listener); } public Object getConstraint(Connection connection) { return realRouter.getConstraint(connection); } public void invalidate(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).invalidate(connection); realRouter.invalidate(connection); } public void route(Connection connection) { boolean consumed = false; for (int i = 0; i < listeners.size(); i++) consumed |= ((RoutingListener) listeners.get(i)) .route(connection); if (!consumed) realRouter.route(connection); for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).postRoute(connection); } public void remove(Connection connection) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).remove(connection); realRouter.remove(connection); } public void setConstraint(Connection connection, Object constraint) { for (int i = 0; i < listeners.size(); i++) ((RoutingListener) listeners.get(i)).setConstraint(connection, constraint); realRouter.setConstraint(connection, constraint); } } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 7846 https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/PolylineConnection.java/#L36-L392 1 848 7846
3413 {"response": "YES I found bad smells", "Detected bad smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private @Metrics(context="metricssystem") public class MetricsSystemImpl extends MetricsSystem implements MetricsSource { static final Log LOG = LogFactory.getLog(MetricsSystemImpl.class); static final String MS_NAME = "MetricsSystem"; static final String MS_STATS_NAME = MS_NAME +",sub=Stats"; static final String MS_STATS_DESC = "Metrics system metrics"; static final String MS_CONTROL_NAME = MS_NAME +",sub=Control"; static final String MS_INIT_MODE_KEY = "hadoop.metrics.init.mode"; enum InitMode { NORMAL, STANDBY } private final Map sources; private final Map allSources; private final Map sinks; private final Map allSinks; private final List callbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private int period; // seconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.info(this.prefix +" metrics system started (again)"); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.info(prefix +" metrics system started in standby mode"); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.info(prefix +" metrics system started"); for (Callback cb : callbacks) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.info(prefix +" metrics system stopped (again)"); return; } for (Callback cb : callbacks) cb.preStop(); LOG.info("Stopping "+ prefix +" metrics system..."); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.info(prefix +" metrics system stopped."); for (Callback cb : callbacks) cb.postStop(); } @Override public synchronized T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { LOG.warn("Sink "+ name +" already exists!"); return sink; } allSinks.put(name, sink); if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); sa.start(); LOG.info("Registered sink "+ name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance( callback.getClass().getClassLoader(), new Class[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback "+ method.getName(), e); } return null; } })); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.save(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period * 1000; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn(e); } } }, millis, millis); LOG.info("Scheduled snapshot period at "+ period +" second(s)."); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.now(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.now() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.now(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.now() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); int confPeriod = 0; for (Entry entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); confPeriod = confPeriod == 0 ? sinkPeriod : ArithmeticUtils.gcd(confPeriod, sinkPeriod); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } period = confPeriod > 0 ? confPeriod : config.getInt(PERIOD_KEY, PERIOD_DEFAULT); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT), conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.info(prefix +" metrics system shutdown complete."); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf((m2 == null ? InitMode.NORMAL.name() : m2) .toUpperCase(Locale.US)); } }
blob data class t t f data class blob 0 6664 https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java/#L69-L601 1 3413 6664
1770    { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } }
blob Data Class, Long Method t f f Data Class, Long Method blob 0 11919 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 1 1770 11919
2566 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } }
blob data class, long method t t f data class, long method blob 0 14868 https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 1 2566 14868
2083 {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JmxSupport { private final static Logger LOGGER = Logger.getLogger(JmxSupport.class.getName()); private static final String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // NOI18N private static final String DIAGNOSTIC_COMMAND_MXBEAN_NAME = "com.sun.management:type=DiagnosticCommand"; // NOI18N private static final String ALL_OBJECTS_OPTION = "-all"; // NOI18N private static final String HISTOGRAM_COMMAND = "gcClassHistogram"; // NOI18N private JvmMXBeans mxbeans; private JmxModel jmxModel; // HotspotDiagnostic private boolean hotspotDiagnosticInitialized; private final Object hotspotDiagnosticLock = new Object(); private HotSpotDiagnosticMXBean hotspotDiagnosticMXBean; private final Object readOnlyConnectionLock = new Object(); private Boolean readOnlyConnection; private Boolean hasDumpAllThreads; private final Object hasDumpAllThreadsLock = new Object(); JmxSupport(JmxModel jmx) { jmxModel = jmx; } private RuntimeMXBean getRuntime() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getRuntimeMXBean(); } return null; } private synchronized JvmMXBeans getJvmMXBeans() { if (mxbeans == null) { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel); } } return mxbeans; } Properties getSystemProperties() { try { RuntimeMXBean runtime = getRuntime(); if (runtime != null) { Properties prop = new Properties(); prop.putAll(runtime.getSystemProperties()); return prop; } return null; } catch (Exception e) { LOGGER.throwing(JmxSupport.class.getName(), "getSystemProperties", e); // NOI18N return null; } } synchronized boolean isReadOnlyConnection() { synchronized (readOnlyConnectionLock) { if (readOnlyConnection == null) { readOnlyConnection = Boolean.FALSE; ThreadMXBean threads = getThreadBean(); if (threads != null) { try { threads.getThreadInfo(1); } catch (SecurityException ex) { readOnlyConnection = Boolean.TRUE; } } } return readOnlyConnection.booleanValue(); } } ThreadMXBean getThreadBean() { JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { return jmx.getThreadMXBean(); } return null; } HotSpotDiagnosticMXBean getHotSpotDiagnostic() { synchronized (hotspotDiagnosticLock) { if (hotspotDiagnosticInitialized) { return hotspotDiagnosticMXBean; } JvmMXBeans jmx = getJvmMXBeans(); if (jmx != null) { try { hotspotDiagnosticMXBean = jmx.getMXBean( ObjectName.getInstance(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME), HotSpotDiagnosticMXBean.class); } catch (MalformedObjectNameException e) { ErrorManager.getDefault().log(ErrorManager.WARNING, "Couldn't find HotSpotDiagnosticMXBean: " + // NOI18N e.getLocalizedMessage()); } catch (IllegalArgumentException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } hotspotDiagnosticInitialized = true; return hotspotDiagnosticMXBean; } } String takeThreadDump(long[] threadIds) { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.getThreadInfo(threadIds, true, true); } else { threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } sb.append(df.format(new Date()) + "\n"); // NOI18N printThreads(sb, threadMXBean, threads); return sb.toString(); } String takeThreadDump() { try { ThreadMXBean threadMXBean = getThreadBean(); if (threadMXBean == null) { return null; } ThreadInfo[] threads; Properties prop = getSystemProperties(); StringBuilder sb = new StringBuilder(4096); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // NOI18N sb.append(df.format(new Date()) + "\n"); sb.append("Full thread dump " + prop.getProperty("java.vm.name") + // NOI18N " (" + prop.getProperty("java.vm.version") + " " + // NOI18N prop.getProperty("java.vm.info") + "):\n"); // NOI18N if (hasDumpAllThreads()) { threads = threadMXBean.dumpAllThreads(true, true); } else { long[] threadIds = threadMXBean.getAllThreadIds(); threads = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE); } printThreads(sb, threadMXBean, threads); return sb.toString(); } catch (Exception e) { LOGGER.log(Level.INFO,"takeThreadDump", e); // NOI18N return null; } } private void printThreads(final StringBuilder sb, final ThreadMXBean threadMXBean, ThreadInfo[] threads) { boolean jdk16 = hasDumpAllThreads(); for (ThreadInfo thread : threads) { if (thread != null) { if (jdk16) { print16Thread(sb, threadMXBean, thread); } else { print15Thread(sb, thread); } } } } private void print16Thread(final StringBuilder sb, final ThreadMXBean threadMXBean, final ThreadInfo thread) { MonitorInfo[] monitors = null; if (threadMXBean.isObjectMonitorUsageSupported()) { monitors = thread.getLockedMonitors(); } sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N sb.append("\n"); // NOI18N int index = 0; for (StackTraceElement st : thread.getStackTrace()) { LockInfo lock = thread.getLockInfo(); String lockOwner = thread.getLockOwnerName(); sb.append("\tat " + st.toString() + "\n"); // NOI18N if (index == 0) { if ("java.lang.Object".equals(st.getClassName()) && // NOI18N "wait".equals(st.getMethodName())) { // NOI18N if (lock != null) { sb.append("\t- waiting on "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } } else if (lock != null) { if (lockOwner == null) { sb.append("\t- parking to wait for "); // NOI18N printLock(sb,lock); sb.append("\n"); // NOI18N } else { sb.append("\t- waiting to lock "); // NOI18N printLock(sb,lock); sb.append(" owned by \""+lockOwner+"\" t@"+thread.getLockOwnerId()+"\n"); // NOI18N } } } printMonitors(sb, monitors, index); index++; } StringBuilder jnisb = new StringBuilder(); printMonitors(jnisb, monitors, -1); if (jnisb.length() > 0) { sb.append(" JNI locked monitors:\n"); sb.append(jnisb); } if (threadMXBean.isSynchronizerUsageSupported()) { sb.append("\n Locked ownable synchronizers:"); // NOI18N LockInfo[] synchronizers = thread.getLockedSynchronizers(); if (synchronizers == null || synchronizers.length == 0) { sb.append("\n\t- None\n"); // NOI18N } else { for (LockInfo li : synchronizers) { sb.append("\n\t- locked "); // NOI18N printLock(sb,li); sb.append("\n"); // NOI18N } } } } private void printMonitors(final StringBuilder sb, final MonitorInfo[] monitors, final int index) { if (monitors != null) { for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == index) { sb.append("\t- locked "); // NOI18N printLock(sb,mi); sb.append("\n"); // NOI18N } } } } private void print15Thread(final StringBuilder sb, final ThreadInfo thread) { sb.append("\n\"" + thread.getThreadName() + // NOI18N "\" - Thread t@" + thread.getThreadId() + "\n"); // NOI18N sb.append(" java.lang.Thread.State: " + thread.getThreadState()); // NOI18N if (thread.getLockName() != null) { sb.append(" on " + thread.getLockName()); // NOI18N if (thread.getLockOwnerName() != null) { sb.append(" owned by: " + thread.getLockOwnerName()); // NOI18N } } sb.append("\n"); // NOI18N for (StackTraceElement st : thread.getStackTrace()) { sb.append(" at " + st.toString() + "\n"); // NOI18N } } private void printLock(StringBuilder sb,LockInfo lock) { String id = Integer.toHexString(lock.getIdentityHashCode()); String className = lock.getClassName(); sb.append("<"+id+"> (a "+className+")"); // NOI18N } boolean takeHeapDump(String fileName) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { try { hsDiagnostic.dumpHeap(fileName,true); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapDump", ex); // NOI18N return false; } return true; } return false; } String getFlagValue(String name) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { VMOption option = hsDiagnostic.getVMOption(name); if (option != null) { return option.getValue(); } } return null; } HeapHistogram takeHeapHistogram() { if (jmxModel.getConnectionState() == ConnectionState.CONNECTED) { MBeanServerConnection conn = jmxModel.getMBeanServerConnection(); try { ObjectName diagCommName = new ObjectName(DIAGNOSTIC_COMMAND_MXBEAN_NAME); if (conn.isRegistered(diagCommName)) { Object histo = conn.invoke(diagCommName, HISTOGRAM_COMMAND, new Object[] {new String[] {ALL_OBJECTS_OPTION}}, new String[] {String[].class.getName()} ); if (histo instanceof String) { return new HeapHistogramImpl((String)histo); } } } catch (MalformedObjectNameException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { LOGGER.log(Level.INFO,"takeHeapHistogram", ex); // NOI18N } catch (InstanceNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (MBeanException ex) { Exceptions.printStackTrace(ex); } catch (ReflectionException ex) { Exceptions.printStackTrace(ex); } } return null; } void setFlagValue(String name, String value) { HotSpotDiagnosticMXBean hsDiagnostic = getHotSpotDiagnostic(); if (hsDiagnostic != null) { hsDiagnostic.setVMOption(name,value); } } private boolean hasDumpAllThreads() { synchronized (hasDumpAllThreadsLock) { if (hasDumpAllThreads == null) { hasDumpAllThreads = Boolean.FALSE; try { ObjectName threadObjName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); MBeanInfo threadInfo = jmxModel.getMBeanServerConnection().getMBeanInfo(threadObjName); if (threadInfo != null) { for (MBeanOperationInfo op : threadInfo.getOperations()) { if ("dumpAllThreads".equals(op.getName())) { hasDumpAllThreads = Boolean.TRUE; } } } } catch (Exception ex) { LOGGER.log(Level.INFO,"hasDumpAllThreads", ex); // NOI18N } } return hasDumpAllThreads.booleanValue(); } } }
blob data class t t f data class blob 0 13077 https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/jmx/src/org/graalvm/visualvm/jmx/impl/JmxSupport.java/#L62-L407 1 2083 13077
247 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("unchecked") public class Utils { public static final String TENANT_IDENTIFIER = "tenantIdentifier=default"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; public static void initializeRESTAssured() { RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("src/main/resources/keystore.jks", "openmf"); } public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into fineract platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); } catch (final Exception e) { if (e instanceof HttpHostConnectException) { final HttpHostConnectException hh = (HttpHostConnectException) e; fail("Failed to connect to fineract platform:" + hh.getMessage()); } throw new RuntimeException(e); } } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static String performGetTextResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); } public static byte[] performGetBinaryResponse(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String getURL){ return given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asByteArray(); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); if (jsonAttributeToGetBack == null) { return (T) json; } return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String deleteURL, final String jsonAttributeToGetBack) { final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() .asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static String convertDateToURLFormat(final String dateToBeConvert) { final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy", Locale.US); final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { final int lengthOfSource = sourceSetString.length(); final Random rnd = new Random(); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); } return (prefix + (sb.toString())); } public static String randomStringGenerator(final String prefix, final int len) { return randomStringGenerator(prefix, len, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { return randomStringGenerator(prefix, lenOfRandomSuffix); } public static Long randomNumberGenerator(final int expectedLength){ final String source="1234567890"; final int lengthofSource=source.length(); final Random random=new Random(); StringBuilder stringBuilder=new StringBuilder(expectedLength); for (int i = 0; i < expectedLength; i++) { stringBuilder.append(source.charAt(random.nextInt(lengthofSource))); } return Long.parseLong(stringBuilder.toString()); } public static String convertDateToURLFormat(final Calendar dateToBeConvert) { DateFormat dateFormat = new SimpleDateFormat("dd MMMMMM yyyy"); dateFormat.setTimeZone(Utils.getTimeZoneOfTenant()); return dateFormat.format(dateToBeConvert.getTime()); } public static LocalDate getLocalDateOfTenant() { LocalDate today = new LocalDate(); final DateTimeZone zone = DateTimeZone.forID(TENANT_TIME_ZONE); if (zone != null) { today = new LocalDate(zone); } return today; } public static TimeZone getTimeZoneOfTenant() { return TimeZone.getTimeZone(TENANT_TIME_ZONE); } public static String performServerTemplatePost(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String postURL,final String legalFormType,final File file,final String locale,final String dateFormat) { final String importDocumentId=given().spec(requestSpec) .queryParam("legalFormType",legalFormType) .multiPart("file",file) .formParam("locale",locale) .formParam("dateFormat",dateFormat) .expect().spec(responseSpec). log().ifError().when().post(postURL) .andReturn().asString(); return importDocumentId; } public static String performServerOutputTemplateLocationGet(final RequestSpecification requestSpec,final ResponseSpecification responseSpec, final String getURL,final String importDocumentId){ final String templateLocation=given().spec(requestSpec). queryParam("importDocumentId",importDocumentId) .expect().spec(responseSpec) .log().ifError().when().get(getURL) .andReturn().asString(); return templateLocation.substring(1,templateLocation.length()-1); } }
blob data class, long method t t f data class, long method blob 0 2657 https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/integrationTest/java/org/apache/fineract/integrationtests/common/Utils.java/#L46-L198 1 247 2657
2151  {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } }
blob data class t t f data class blob 0 13293 https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 1 2151 13293
3728 {"result":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList<>(); private String resourceBundleName; private volatile boolean useParentHandlers = true; private volatile Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. @Weak private volatile Logger parent; // our nearest parent. private ArrayList kids; // WeakReferences to loggers that have us as parent private volatile Level levelObject; private volatile int levelValue; // current effective level value private WeakReference callersClassLoaderRef; /** * GLOBAL_LOGGER_NAME is a name for the global logger. * * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. * * @return global logger object * @since 1.7 */ public static final Logger getGlobal() { return global; } /** * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * The preferred way to get the global logger object is via the call * Logger.getGlobal(). * For compatibility with old JDK versions where the * Logger.getGlobal() is not available use the call * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) * or Logger.getLogger("global"). */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** * Protected method to construct a logger for a named subsystem. * * The logger will be initially configured with a null Level * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this(name, resourceBundleName, null); } Logger(String name, String resourceBundleName, Class caller) { this.manager = LogManager.getLogManager(); setupResourceInfo(resourceBundleName, caller); this.name = name; levelValue = Level.INFO.intValue(); } /* J2ObjC removed. private void setCallersClassLoaderRef(Class caller) { ClassLoader callersClassLoader = ((caller != null) ? caller.getClassLoader() : null); if (callersClassLoader != null) { this.callersClassLoaderRef = new WeakReference(callersClassLoader); } } */ private ClassLoader getCallersClassLoader() { return (callersClassLoaderRef != null) ? callersClassLoaderRef.get() : null; } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager. to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkPermission() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkPermission(); } } // Until all JDK code converted to call sun.util.logging.PlatformLogger // (see 7054233), we need to determine if Logger.getLogger is to add // a system logger or user logger. // // As an interim solution, if the immediate caller whose caller loader is // null, we assume it's a system logger and add it to the system context. // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class LoggerHelper { static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); // workaround to turn on the old behavior for resource bundle search static boolean allowStackWalkSearch = getBooleanProperty("jdk.logging.allowStackWalkSearch"); private static boolean getBooleanProperty(final String key) { /* J2ObjC removed. String s = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(key); } }); */ String s = System.getProperty(key); return Boolean.valueOf(s); } } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { LogManager manager = LogManager.getLogManager(); /* J2ObjC modified. SecurityManager sm = System.getSecurityManager(); if (sm != null && !LoggerHelper.disableCallerCheck) { */ if (caller != null && !LoggerHelper.disableCallerCheck) { if (caller.getClassLoader() == null) { return manager.demandSystemLogger(name, resourceBundleName); } } return manager.demandLogger(name, resourceBundleName, caller); // ends up calling new Logger(name, resourceBundleName, caller) // iff the logger doesn't exist already } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name) { // This method is intentionally not a wrapper around a call // to getLogger(name, resourceBundleName). If it were then // this sequence: // // getLogger("Foo", "resourceBundleForFoo"); // getLogger("Foo"); // // would throw an IllegalArgumentException in the second call // because the wrapper would result in an attempt to replace // the existing "resourceBundleForFoo" with null. // // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. return demandLogger(name, null, VMStack.getStackClass1()); */ return demandLogger(name, null, null); } /** * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent's Handlers. It will be registered in * the LogManager global namespace. * * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ // Synchronization is not required here. All synchronization for // adding a new Logger object is handled by LogManager.addLogger(). @CallerSensitive public static Logger getLogger(String name, String resourceBundleName) { // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Class callerClass = VMStack.getStackClass1(); */ Class callerClass = null; Logger result = demandLogger(name, resourceBundleName, callerClass); if (result.resourceBundleName == null) { // We haven't set a bundle name yet on the Logger, so it's ok to proceed. // We have to set the callers ClassLoader here in case demandLogger // above found a previously created Logger. This can happen, for // example, if Logger.getLogger(name) is called and subsequently // Logger.getLogger(name, resourceBundleName) is called. In this case // we won't necessarily have the correct classloader saved away, so // we need to set it here, too. // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName, callerClass); } else if (!result.resourceBundleName.equals(resourceBundleName)) { // We already had a bundle name on the Logger and we're trying // to change it here which is not allowed. throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } // package-private // Add a platform logger to the system context. // i.e. caller of sun.util.logging.PlatformLogger.getLogger static Logger getPlatformLogger(String name) { LogManager manager = LogManager.getLogManager(); // all loggers in the system context will default to // the system logger's resource bundle Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); return result; } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ // Synchronization is not required here. All synchronization for // adding a new anonymous Logger object is handled by doSetParent(). @CallerSensitive public static Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); // Android-changed: Use VMStack.getStackClass1. /* J2ObjC modified. Logger result = new Logger(null, resourceBundleName, VMStack.getStackClass1()); */ Logger result = new Logger(null, resourceBundleName, null); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName(), true); } /** * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** * Set a filter to control output on this Logger. * * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setFilter(Filter newFilter) throws SecurityException { checkPermission(); filter = newFilter; } /** * Get the current filter for this Logger. * * @return a filter object (may be null) */ public Filter getFilter() { return filter; } /** * Log a LogRecord. * * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } Filter theFilter = filter; if (theFilter != null && !theFilter.isLoggable(record)) { return; } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { for (Handler handler : logger.getHandlers()) { handler.publish(record); } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname, true)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** * Log a message, with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** * Log a message, with one object parameter. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** * Log a message, with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** * Log a message, specifying source class and method, * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** * Log a message, specifying source class and method, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** * Log a message, specifying source class and method, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname, false)); } log(lr); } /** * Log a message, specifying source class, method, and resource bundle name * with no arguments. * * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** * Log a method entry. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** * Log a method entry, with one parameter. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** * Log a method entry, with an array of parameters. * * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** * Log a method return. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** * Log a method return, with result object. * * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** * Log throwing an exception. * * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** * Log a SEVERE message. * * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** * Log a WARNING message. * * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** * Log an INFO message. * * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** * Log a CONFIG message. * * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** * Log a FINE message. * * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** * Log a FINER message. * * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** * Log a FINEST message. * * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkPermission(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** * Get the name for this logger. * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** * Add a log Handler to receive logging messages. * * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkPermission(); handlers.add(handler); } /** * Remove a log Handler. * * Returns silently if the given Handler is not found or is null * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removeHandler(Handler handler) throws SecurityException { checkPermission(); if (handler == null) { return; } handlers.remove(handler); } /** * Get the Handlers associated with this logger. * * @return an array of all registered Handlers */ public Handler[] getHandlers() { return handlers.toArray(emptyHandlers); } /** * Specify whether or not this logger should send its output * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setUseParentHandlers(boolean useParentHandlers) { checkPermission(); this.useParentHandlers = useParentHandlers; } /** * Discover whether or not this logger is sending its output * to its parent logger. * * @return true if output is to be sent to the logger's parent */ public boolean getUseParentHandlers() { return useParentHandlers; } static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; private static ResourceBundle findSystemResourceBundle(final Locale locale) { // J2ObjC: inlined contents of sun/util/logging/resources/logging/logging.properties return new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[][] { { "ALL", "ALL" }, { "SEVERE", "SEVERE" }, { "WARNING", "WARNING" }, { "INFO", "INFO" }, { "CONFIG", "CONFIG" }, { "FINE", "FINE" }, { "FINER", "FINER" }, { "FINEST", "FINEST" }, { "OFF", "OFF" } }; } }; } /** * Private utility method to map a resource bundle name to an * actual resource bundle, using a simple one-entry cache. * Returns null for a null name. * May also return null if we can't find the resource bundle and * there is no suitable previous cached value. * * @param name the ResourceBundle to locate * @param userCallersClassLoader if true search using the caller's ClassLoader * @return ResourceBundle specified by name or null if not found */ private synchronized ResourceBundle findResourceBundle(String name, boolean useCallersClassLoader) { // For all lookups, we first check the thread context class loader // if it is set. If not, we use the system classloader. If we // still haven't found it we use the callersClassLoaderRef if it // is set and useCallersClassLoader is true. We set // callersClassLoaderRef initially upon creating the logger with a // non-null resource bundle name. // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale.equals(catalogLocale) && name.equals(catalogName)) { return catalog; } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { catalog = findSystemResourceBundle(currentLocale); catalogName = name; catalogLocale = currentLocale; return catalog; } // Use the thread's context ClassLoader. If there isn't one, use the // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // We can't find the ResourceBundle in the default // ClassLoader. Drop through. } /* J2ObjC removed: J2ObjC only has one class loader. if (useCallersClassLoader) { // Try with the caller's ClassLoader ClassLoader callersClassLoader = getCallersClassLoader(); if (callersClassLoader != null && callersClassLoader != cl) { try { catalog = ResourceBundle.getBundle(name, currentLocale, callersClassLoader); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { } } } // If -Djdk.logging.allowStackWalkSearch=true is set, // does stack walk to search for the resource bundle if (LoggerHelper.allowStackWalkSearch) { return findResourceBundleFromStack(name, currentLocale, cl); } else { return null; } */ return null; } /** * This method will fail when running with a VM that enforces caller-sensitive * methods and only allows to get the immediate caller. */ /* J2ObjC removed. @CallerSensitive private synchronized ResourceBundle findResourceBundleFromStack(String name, Locale locale, ClassLoader cl) { // Android-changed: Use VMStack.getThreadStackTrace. StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); for (int ix = 0; ; ix++) { Class clz = null; try { clz = Class.forName(stack[ix].getClassName()); } catch (ClassNotFoundException ignored) {} if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, locale, cl); catalogName = name; catalogLocale = locale; return catalog; } catch (MissingResourceException ex) { } } return null; } */ // Private utility method to initialize our one entry // resource bundle name cache and the callers ClassLoader // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // resourceBundleName field. // Synchronized to prevent races in setting the fields. private synchronized void setupResourceInfo(String name, Class callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** * Return the parent for this Logger. * * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * * The result will be null if it is called on the root Logger * in the namespace. * * @return nearest existing parent Logger */ public Logger getParent() { // Note: this used to be synchronized on treeLock. However, this only // provided memory semantics, as there was no guarantee that the caller // would synchronize on treeLock (in fact, there is no way for external // callers to so synchronize). Therefore, we have made parent volatile // instead. return parent; } /** * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * * It should not be called from application code. * * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkPermission(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } }
blob data class, long method t t f data class, long method blob 0 9201 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java/#L180-L1727 1 3728 9201
414      { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TimingEvent { public static class LauncherTimings { public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer"; public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String JOB_ORCHESTRATED = "JobOrchestrated"; public static final String JOB_PREPARE = "JobPrepareTimer"; public static final String JOB_START = "JobStartTimer"; public static final String JOB_RUN = "JobRunTimer"; public static final String JOB_COMMIT = "JobCommitTimer"; public static final String JOB_CLEANUP = "JobCleanupTimer"; public static final String JOB_CANCEL = "JobCancelTimer"; public static final String JOB_COMPLETE = "JobCompleteTimer"; public static final String JOB_FAILED = "JobFailedTimer"; public static final String JOB_SUCCEEDED = "JobSucceededTimer"; } public static class RunJobTimings { public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer"; public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer"; public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer"; public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer"; public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer"; public static final String MR_JOB_SETUP = "JobMrSetupTimer"; public static final String MR_JOB_RUN = "JobMrRunTimer"; public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer"; public static final String HELIX_JOB_RUN = "JobHelixRunTimer"; } public static class FlowTimings { public static final String FLOW_COMPILED = "FlowCompiled"; public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed"; } public static class FlowEventConstants { public static final String FLOW_NAME_FIELD = "flowName"; public static final String FLOW_GROUP_FIELD = "flowGroup"; public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId"; public static final String JOB_NAME_FIELD = "jobName"; public static final String JOB_GROUP_FIELD = "jobGroup"; public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId"; public static final String SPEC_EXECUTOR_FIELD = "specExecutor"; public static final String LOW_WATERMARK_FIELD = "lowWatermark"; public static final String HIGH_WATERMARK_FIELD = "highWatermark"; public static final String PROCESSED_COUNT_FIELD = "processedCount"; } public static final String METADATA_START_TIME = "startTime"; public static final String METADATA_END_TIME = "endTime"; public static final String METADATA_DURATION = "durationMillis"; public static final String METADATA_TIMING_EVENT = "timingEvent"; public static final String METADATA_MESSAGE = "message"; private final String name; private final Long startTime; private final EventSubmitter submitter; private boolean stopped; public TimingEvent(EventSubmitter submitter, String name) { this.stopped = false; this.name = name; this.submitter = submitter; this.startTime = System.currentTimeMillis(); } /** * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op. */ public void stop() { stop(Maps. newHashMap()); } /** * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped * before, this is a no-op. * * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event */ public void stop(Map additionalMetadata) { if (this.stopped) { return; } this.stopped = true; long endTime = System.currentTimeMillis(); long duration = endTime - this.startTime; Map finalMetadata = Maps.newHashMap(); finalMetadata.putAll(additionalMetadata); finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT); finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime)); finalMetadata.put(METADATA_END_TIME, Long.toString(endTime)); finalMetadata.put(METADATA_DURATION, Long.toString(duration)); this.submitter.submit(this.name, finalMetadata); } }
blob long method, data class t t f long method, data class blob 0 4220 https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java/#L28-L124 1 414 4220
245     {
"message": "YES I found bad smells",
"bad smells are": [
"Long method",
"Duplicate code",
"Data class",
"Feature envy"
]
}
I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } }
blob long method, duplicate code, data class, feature envy t t f long method, duplicate code, data class, feature envy blob 0 2653 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 2 245 2653
145 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("all") public abstract class AbstractEntitiesRuntimeModule extends DefaultXbaseRuntimeModule { protected Properties properties = null; @Override public void configure(Binder binder) { properties = tryBindProperties(binder, "org/eclipse/xtext/idea/example/entities/Entities.properties"); super.configure(binder); } public void configureLanguageName(Binder binder) { binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.idea.example.entities.Entities"); } public void configureFileExtensions(Binder binder) { if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null) binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("entities"); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public ClassLoader bindClassLoaderToInstance() { return getClass().getClassLoader(); } // contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2 public Class bindIGrammarAccess() { return EntitiesGrammarAccess.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISemanticSequencer() { return EntitiesSemanticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISyntacticSequencer() { return EntitiesSyntacticSequencer.class; } // contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2 public Class bindISerializer() { return Serializer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIParser() { return EntitiesParser.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenToStringConverter() { return AntlrTokenToStringConverter.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindIAntlrTokenFileProvider() { return EntitiesAntlrTokenFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindLexer() { return InternalEntitiesLexer.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class bindITokenDefProvider() { return AntlrTokenDefProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Provider provideInternalEntitiesLexer() { return LexerProvider.create(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureRuntimeLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerBindings.RUNTIME)) .to(InternalEntitiesLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2 @SingletonBinding(eager=true) public Class bindEntitiesValidator() { return EntitiesValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public Class bindIBatchScopeProvider() { return EntitiesScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIScopeProviderDelegate(Binder binder) { binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(XImportSectionNamespaceScopeProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 public void configureIgnoreCaseLinking(Binder binder) { binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIContainer$Manager() { return StateBasedContainerManager.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public Class bindIAllContainersState$Provider() { return ResourceSetBasedAllContainersStateProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptions(Binder binder) { binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2 public void configureIResourceDescriptionsPersisted(Binder binder) { binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class); } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public Class bindIFormatter2() { return EntitiesFormatter.class; } // contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2 public void configureFormatterPreferences(Binder binder) { binder.bind(IPreferenceValuesProvider.class).annotatedWith(FormatterPreferences.class).to(FormatterPreferenceValuesProvider.class); } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIQualifiedNameProvider() { return XbaseQualifiedNameProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindILocationInFileProvider() { return JvmLocationInFileProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIGlobalScopeProvider() { return TypesAwareDefaultGlobalScopeProvider.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindFeatureNameValidator() { return LogicalContainerAwareFeatureNameValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultBatchTypeResolver() { return LogicalContainerAwareBatchTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindDefaultReentrantTypeResolver() { return LogicalContainerAwareReentrantTypeResolver.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIResourceValidator() { return DerivedStateAwareResourceValidator.class; } // contributed by org.eclipse.xtext.xtext.generator.xbase.XbaseGeneratorFragment2 public Class bindIJvmModelInferrer() { return EntitiesJvmModelInferrer.class; } }
blob long method, data class t t f long method, data class blob 0 1809 https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.example.entities/src-gen/org/eclipse/xtext/idea/example/entities/AbstractEntitiesRuntimeModule.java/#L76-L249 1 145 1809
60
{
"response": "YES I found bad smells",
"the bad smells are": [
"Long method",
"Long parameter list",
"Switch statements",
"Data class",
"Data clumps"
]
}
I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } }
blob long method, long parameter list, switch statements, data class, data clumps t t f long method, long parameter list, switch statements, data class, data clumps blob 0 1007 https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 2 60 1007
2633  YES I found bad smells the bad smells are: 1.Long method, 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } }
long method Long method, 2Large parameter list, 3Magic numbers, 4Data class, 5Switch statement, 6Duplicate code t f t  2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code.   0 15109 https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 2 2633 15109
703   YES I found bad smells the bad smells are: 1. Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it. This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself. 2. Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code. This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability. 3. Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code. It would be better to group the related parameters into separate objects and pass them instead. 4. Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic. This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class. 5. Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks. This should be simplified for better readability and maintainability. 6. Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri. This indicates that this logic can be extracted into a separate method to avoid repetition. 7. Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc. These should be replaced with proper objects for better readability and maintainability. 8. Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors. 9. Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues. 10. Non-meaningful comments: The comments in the setter methods of RemoteProcessGroupDTO class are not helpful and do not provide any additional information. This could be considered as unnecessary clutter in the code. I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
@XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } }
blob  Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself2 Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability3 Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code It would be better to group the related parameters into separate objects and pass them instead4 Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class5 Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks This should be simplified for better readability and maintainability6 Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri This indicates that this logic can be extracted into a separate method to avoid repetition7 Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc These should be replaced with proper objects for better readability and maintainability8 Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors9 Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues t f f . Feature envy: The RemoteProcessGroupDTO class is accessing and manipulating the data from ComponentDTO class, even though it extends from it. This indicates that the logic for handling ComponentDTO data should be moved to ComponentDTO class itself.2. Long method: The RemoteProcessGroupDTO class has a long constructor with multiple lines of code. This indicates that the logic inside the constructor should be refactored into smaller methods for better readability and maintainability.3. Long parameter list: The constructor and setters in RemoteProcessGroupDTO class have a large number of parameters, making it difficult to understand and maintain the code. It would be better to group the related parameters into separate objects and pass them instead.4. Data class: The RemoteProcessGroupDTO class is just a container for holding data and does not have any behavior or logic. This indicates that it should be refactored into a data structure like a POJO or DTO instead of a class.5. Complex conditional logic: The logic inside the getTargetUri() and getTargetUris() methods is unnecessarily complex with multiple if statements and synchronized blocks. This should be simplified for better readability and maintainability.6. Code repetition: The getTargetUri() and getTargetUris() methods have similar logic for handling the target uri. This indicates that this logic can be extracted into a separate method to avoid repetition.7. Primitive obsession: The RemoteProcessGroupDTO class is using primitive data types like String and Integer for complex concepts like TargetUri, TargetUris, Timeout, etc. These should be replaced with proper objects for better readability and maintainability.8. Inconsistent variable naming: The RemoteProcessGroupDTO class has inconsistent naming for some variables like "targetUris" and "targetUri" which can lead to confusion and errors.9. Lack of encapsulation: The RemoteProcessGroupDTO class has public getters and setters for its fields, which goes against the principles of encapsulation and can lead to data integrity issues. blob 0 6698 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 2 703 6698
1243  {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@ThreadSafe public final class MetricsFactory { private static final UtilCache METRICS_CACHE = UtilCache.createUtilCache("base.metrics", 0, 0); /** * A "do-nothing" Metrics instance. */ public static final Metrics NULL_METRICS = new NullMetrics(); /** * Creates a Metrics instance based on element attributes. * If an instance with the same name already exists, it will be returned. * * Element Attributes * Attribute NameRequirementsDescriptionNotes * * name * Required * The metric name. *   * * estimation-size * Optional * Positive integer number of events to include in the metrics calculation. * Defaults to "100". * * * estimation-time * Optional * Positive integer number of milliseconds to include in the metrics calculation. * Defaults to "1000". * * * smoothing * Optional * Smoothing factor - used to smooth the differences between calculations. * A value of "1" disables smoothing. Defaults to "0.7". * * * threshold * Optional * The metric threshold. The meaning of the threshold is determined by client code. * Defaults to "0.0". * * * @param element The element whose attributes will be used to create the Metrics instance * @return A Metrics instance based on element attributes * @throws IllegalArgumentException if element is null or if the name attribute is empty * @throws NumberFormatException if any of the numeric attribute values are unparsable */ public static Metrics getInstance(Element element) { Assert.notNull("element", element); String name = element.getAttribute("name"); Assert.notEmpty("name attribute", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { int estimationSize = UtilProperties.getPropertyAsInteger("serverstats", "metrics.estimation.size", 100); String attributeValue = element.getAttribute("estimation-size"); if (!attributeValue.isEmpty()) { estimationSize = Integer.parseInt(attributeValue); } long estimationTime = UtilProperties.getPropertyAsLong("serverstats", "metrics.estimation.time", 1000); attributeValue = element.getAttribute("estimation-time"); if (!attributeValue.isEmpty()) { estimationTime = Long.parseLong(attributeValue); } double smoothing = UtilProperties.getPropertyNumber("serverstats", "metrics.smoothing.factor", 0.7); attributeValue = element.getAttribute("smoothing"); if (!attributeValue.isEmpty()) { smoothing = Double.parseDouble(attributeValue); } double threshold = 0.0; attributeValue = element.getAttribute("threshold"); if (!attributeValue.isEmpty()) { threshold = Double.parseDouble(attributeValue); } result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Creates a Metrics instance. * If an instance with the same name already exists, it will be returned. * @param name The metric name. * @param estimationSize Positive integer number of events to include in the metrics calculation. * @param estimationTime Positive integer number of milliseconds to include in the metrics calculation. * @param smoothing Smoothing factor - used to smooth the differences between calculations. * @return A Metrics instance */ public static Metrics getInstance(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { Assert.notNull("name", name); Metrics result = METRICS_CACHE.get(name); if (result == null) { result = new MetricsImpl(name, estimationSize, estimationTime, smoothing, threshold); METRICS_CACHE.putIfAbsent(name, result); result = METRICS_CACHE.get(name); } return result; } /** * Returns an existing Metric instance with the specified name. * Returns null if the metric does not exist. * @param name The metric name */ public static Metrics getMetric(String name) { Assert.notNull("name", name); return METRICS_CACHE.get(name); } /** * Returns all Metric instances, sorted by name. */ public static Collection getMetrics() { return new TreeSet(METRICS_CACHE.values()); } private static final class MetricsImpl implements Metrics, Comparable { private int count = 0; private long lastTime = System.currentTimeMillis(); private double serviceRate = 0.0; private long totalServiceTime = 0; private long totalEvents = 0; private long cumulativeEvents = 0; private final String name; private final int estimationSize; private final long estimationTime; private final double smoothing; private final double threshold; private MetricsImpl(String name, int estimationSize, long estimationTime, double smoothing, double threshold) { this.name = name; this.estimationSize = estimationSize; this.estimationTime = estimationTime; this.smoothing = smoothing; this.threshold = threshold; } @Override public int compareTo(Metrics other) { return this.name.compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } try { MetricsImpl that = (MetricsImpl) obj; return this.name.equals(that.name); } catch (Exception e) {} return false; } @Override public String getName() { return name; } @Override public synchronized double getServiceRate() { return serviceRate; } @Override public double getThreshold() { return threshold; } @Override public synchronized long getTotalEvents() { return cumulativeEvents; } @Override public int hashCode() { return name.hashCode(); } @Override public synchronized void recordServiceRate(int numEvents, long time) { totalEvents += numEvents; cumulativeEvents += numEvents; totalServiceTime += time; count++; long curTime = System.currentTimeMillis(); if ((count == estimationSize) || (curTime - lastTime >= estimationTime)) { if (totalEvents == 0) { totalEvents = 1; } double rate = totalServiceTime / totalEvents; serviceRate = (rate * smoothing) + (serviceRate * (1.0 - smoothing)); count = 0; lastTime = curTime; totalEvents = totalServiceTime = 0; } } @Override public synchronized void reset() { serviceRate = 0.0; count = 0; lastTime = System.currentTimeMillis(); totalEvents = totalServiceTime = cumulativeEvents = 0; } @Override public String toString() { return name; } } private static final class NullMetrics implements Metrics { @Override public String getName() { return "NULL"; } @Override public double getServiceRate() { return 0; } @Override public double getThreshold() { return 0.0; } @Override public long getTotalEvents() { return 0; } @Override public void recordServiceRate(int numEvents, long time) { } @Override public void reset() { } } private MetricsFactory() {} }
blob data class t t f data class blob 0 10415 https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/base/src/main/java/org/apache/ofbiz/base/metrics/MetricsFactory.java/#L43-L290 1 1243 10415
872  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } }
long method long method, data class t t t  data class   0 7980 https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 1 872 7980
1437                  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); }
long method long method, data class t t t  data class   0 10965 https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 1 1437 10965
1732  YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Duplicate code 6. Magic numbers (e.g. 32) 7. Poor naming (e.g. variables like "ent" and "iter") 8. Indicators of complex or confusing logic (e.g. multiple if statements checking for different conditions) 9. Comments left in the code (e.g. promise to remove println) 10. Use of non-descriptive or ambiguous variable names (e.g. "dst" or "src") 11. Lack of proper exception handling (e.g. if (ent.getType() == LogEntry.Type.TXN) throws an unchecked exception). I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } }
long method  Long method2 Feature envy 3 Data class4 Primitive obsession5 Duplicate code6 Magic numbers (eg 32)7 Poor naming (eg variables like "ent" and "iter")8 Indicators of complex or confusing logic (eg multiple if statements checking for different conditions)9 Comments left in the code (eg promise to remove println) t f t     0 11821 https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 2 1732 11821
184 {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ServletContextListenerStartup implements ServletContextListener { /** Configuration file path parameter name. */ public static final String IGNITE_CFG_FILE_PATH_PARAM = "IgniteConfigurationFilePath"; /** Names of started Ignite instances. */ private final Collection igniteInstanceNames = new ArrayList<>(); /** {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent evt) { ServletContext ctx = evt.getServletContext(); String cfgFile = ctx.getInitParameter(IGNITE_CFG_FILE_PATH_PARAM); Collection cfgs; GridSpringResourceContext rsrcCtx = null; if (cfgFile != null) { URL cfgUrl = null; try { cfgUrl = evt.getServletContext().getResource("/META-INF/" + cfgFile); } catch (MalformedURLException ignored) { // Ignore, we still need to try with IGNITE_HOME. } if (cfgUrl == null) // Try with IGNITE_HOME and with context class loader. cfgUrl = U.resolveIgniteUrl(cfgFile); if (cfgUrl == null) throw new IgniteException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile); IgniteBiTuple, ? extends GridSpringResourceContext> t; try { t = IgnitionEx.loadConfigurations(cfgUrl); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to load Ignite configuration.", e); } cfgs = t.get1(); rsrcCtx = t.get2(); if (cfgs.isEmpty()) throw new IgniteException("Can't find grid factory configuration in: " + cfgUrl); } else cfgs = Collections.singleton(new IgniteConfiguration()); try { assert !cfgs.isEmpty(); for (IgniteConfiguration cfg : cfgs) { assert cfg != null; Ignite ignite; synchronized (ServletContextListenerStartup.class) { try { ignite = G.ignite(cfg.getIgniteInstanceName()); } catch (IgniteIllegalStateException ignored) { ignite = IgnitionEx.start(new IgniteConfiguration(cfg), rsrcCtx); } } // Check if grid is not null - started properly. if (ignite != null) igniteInstanceNames.add(ignite.name()); } } catch (IgniteCheckedException e) { // Stop started grids only. for (String name : igniteInstanceNames) G.stop(name, true); throw new IgniteException("Failed to start Ignite.", e); } } /** {@inheritDoc} */ @Override public void contextDestroyed(ServletContextEvent evt) { // Stop started grids only. for (String name: igniteInstanceNames) G.stop(name, true); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ServletContextListenerStartup.class, this); } }
blob data class, long method t t f data class, long method blob 0 2104 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/web/src/main/java/org/apache/ignite/startup/servlet/ServletContextListenerStartup.java/#L95-L189 1 184 2104
5536  YES I found bad smells. The bad smells are: 1. Feature Envy; 2. Data Class. The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); }
feature envy  Feature Envy;2 Data Class t f t     0 6190 https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 1 5536 6190
1311  {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); }
long method long method, data class t t t  data class   0 10681 https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 1 1311 10681
4484   YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent naming 5. Excessive comments 6. Inconsistent formatting 7. Complex conditional logic 8. Complex nested loops 9. Data class 10. Message chains 11. Excessive parameters 12. Inadequate naming 13. Inconsistent error handling 14. Improper exception handling 15. Poor separation of concerns 16. Excessive use of public fields/variables 17. Excessive use of null checks 18. Inconsistent use of types 19. Inconsistent use of language features 20. Magic numbers/strings 21. Unused variables/parameters 22. Dead code I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } }
blob  Long method2 Feature envy3 Duplicated code4 Inconsistent naming5 Excessive comments6 Inconsistent formatting7 Complex conditional logic8 Complex nested loops9 Data class t f f . Long method2. Feature envy3. Duplicated code4. Inconsistent naming5. Excessive comments6. Inconsistent formatting7. Complex conditional logic8. Complex nested loops9. Data class blob 0 11873 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 2 4484 11873
2025    { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static void listZookeeper(ServerContext context) throws Exception { System.out.println("Listing volumes referenced in zookeeper"); TreeSet volumes = new TreeSet<>(); volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir(context))); ArrayList result = new ArrayList<>(); MetadataTableUtil.getRootLogEntries(context, result); for (LogEntry logEntry : result) { getLogURIs(volumes, logEntry); } for (String volume : volumes) System.out.println("\tVolume : " + volume); }
feature envy long method, data class t t f long method, data class feature envy 0 12800 https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/ListVolumesUsed.java/#L61-L75 1 2025 12800
1894  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; }
blob long method, data class t t f long method, data class blob 0 12321 https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 1 1894 12321
5233 { "YES I found bad smells": true, "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } }
blob data class, long method t t f data class, long method blob 0 14632 https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 1 5233 14632
3248  {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } }
blob data class, long method t t f data class, long method blob 0 5487 https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 1 3248 5487
192 {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class FuncLongToString extends VectorExpression { private static final long serialVersionUID = 1L; private final int inputColumn; // Transient members initialized by transientInit method. protected byte[] bytes; FuncLongToString(int inputColumn, int outputColumnNum) { super(outputColumnNum); this.inputColumn = inputColumn; } FuncLongToString() { super(); // Dummy final assignments. inputColumn = -1; } @Override public void transientInit() throws HiveException { super.transientInit(); bytes = new byte[64]; // staging area for results, to avoid new() calls } @Override public void evaluate(VectorizedRowBatch batch) throws HiveException { if (childExpressions != null) { super.evaluateChildren(batch); } LongColumnVector inputColVector = (LongColumnVector) batch.cols[inputColumn]; int[] sel = batch.selected; int n = batch.size; long[] vector = inputColVector.vector; BytesColumnVector outputColVector = (BytesColumnVector) batch.cols[outputColumnNum]; outputColVector.initBuffer(); boolean[] inputIsNull = inputColVector.isNull; boolean[] outputIsNull = outputColVector.isNull; if (n == 0) { //Nothing to do return; } // We do not need to do a column reset since we are carefully changing the output. outputColVector.isRepeating = false; if (inputColVector.isRepeating) { if (inputColVector.noNulls || !inputIsNull[0]) { // Set isNull before call in case it changes it mind. outputIsNull[0] = false; prepareResult(0, vector, outputColVector); } else { outputIsNull[0] = true; outputColVector.noNulls = false; } outputColVector.isRepeating = true; return; } if (inputColVector.noNulls) { if (batch.selectedInUse) { // CONSIDER: For large n, fill n or all of isNull array and use the tighter ELSE loop. if (!outputColVector.noNulls) { for(int j = 0; j != n; j++) { final int i = sel[j]; // Set isNull before call in case it changes it mind. outputIsNull[i] = false; prepareResult(i, vector, outputColVector); } } else { for(int j = 0; j != n; j++) { final int i = sel[j]; prepareResult(i, vector, outputColVector); } } } else { if (!outputColVector.noNulls) { // Assume it is almost always a performance win to fill all of isNull so we can // safely reset noNulls. Arrays.fill(outputIsNull, false); outputColVector.noNulls = true; } for(int i = 0; i != n; i++) { prepareResult(i, vector, outputColVector); } } } else /* there are nulls in the inputColVector */ { // Carefully handle NULLs... outputColVector.noNulls = false; if (batch.selectedInUse) { for(int j=0; j != n; j++) { int i = sel[j]; outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } else { for(int i = 0; i != n; i++) { outputColVector.isNull[i] = inputColVector.isNull[i]; if (!inputColVector.isNull[i]) { prepareResult(i, vector, outputColVector); } } } } } /* Evaluate result for position i (using bytes[] to avoid storage allocation costs) * and set position i of the output vector to the result. */ abstract void prepareResult(int i, long[] vector, BytesColumnVector outputColVector); @Override public String vectorExpressionParameters() { return getColumnParamString(0, inputColumn); } @Override public VectorExpressionDescriptor.Descriptor getDescriptor() { return (new VectorExpressionDescriptor.Builder()).setMode( VectorExpressionDescriptor.Mode.PROJECTION).setNumArguments(1).setInputExpressionTypes( VectorExpressionDescriptor.InputExpressionType.COLUMN).setArgumentTypes( VectorExpressionDescriptor.ArgumentType.INT_FAMILY).build(); } }
blob data class t t f data class blob 0 2216 https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/expressions/FuncLongToString.java/#L36-L172 1 192 2216
2447 {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); }
long method data class, long method t t t data class   0 14497 https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 1 2447 14497
1460      { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); }
feature envy long method, data class t t f long method, data class feature envy 0 11021 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 1 1460 11021
91  {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Controller public class SignupController { private final SignupHelper signupHelper; @Inject public SignupController(AccountRepository accountRepository, SignedUpGateway gateway) { this.signupHelper = new SignupHelper(accountRepository, gateway); } /** * Render a signup form to the person as HTML in their web browser. */ @RequestMapping(value="/signup", method=RequestMethod.GET) public SignupForm signupForm(WebRequest request) { Connection connection = ProviderSignInUtils.getConnection(request); if (connection != null) { request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Greenhouse account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST); return SignupForm.fromProviderUser(connection.fetchUserProfile()); } else { return new SignupForm(); } } /** * Process a signup form submission. * Delegate to a {@link SignupHelper} to actually complete the signin transaction. * Redirects the new member to the application home page on successful sign-in. */ @RequestMapping(value="/signup", method=RequestMethod.POST) public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) { if (formBinding.hasErrors()) { return null; } boolean result = signupHelper.signup(form, formBinding, new SignupCallback() { public void postSignup(Account account) { ProviderSignInUtils.handlePostSignUp(account.getId().toString(), request); } }); return result ? "redirect:/" : null; } @RequestMapping(value="/signup", method=RequestMethod.POST, consumes="application/json") public ResponseEntity> signupFromApi(@RequestBody SignupForm form) { BindingResult formBinding = validate(form); // Temporary manual validation until SPR-9826 is fixed. if (formBinding.hasErrors()) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Validation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } boolean result = signupHelper.signup(form, formBinding); if (result) { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account created"); return new ResponseEntity>(errorResponse, HttpStatus.CREATED); } else { HashMap errorResponse = new HashMap(); errorResponse.put("message", "Account creation error"); errorResponse.put("errors", getErrorsMap(formBinding)); return new ResponseEntity>(errorResponse, HttpStatus.BAD_REQUEST); } } private BindException validate(SignupForm form) { BindException errors; errors = new BindException(form, "signupForm"); LazyValidatorFactory lvf = new LazyValidatorFactory(); Validator validator = new SpringValidatorAdapter(lvf.getValidator()); ValidationUtils.invokeValidator(validator, form, errors); return errors; } private List> getErrorsMap(BindingResult formBinding) { List fieldErrors = formBinding.getFieldErrors(); List> errors = new ArrayList>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map fieldErrorMap = new HashMap(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap); } return errors; } }
blob data class, long method t t f data class, long method blob 0 1242 https://github.com/spring-projects/greenhouse/blob/c7994183812150de971ef4a76c08d5b4631ab5d1/src/main/java/com/springsource/greenhouse/signup/SignupController.java/#L54-L143 1 91 1242
580    { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; }
feature envy 1. long method, 2. data class t t f 1. long method, 2. data class feature envy 0 5785 https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 1 580 5785
2596      { "response": "YES I found bad smells" , "the bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall { @Child private LoopNode loop; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) { super(src, operator); this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode())); } @Override public Object execute(VirtualFrame frame) { loop.executeLoop(frame); visibility.execute(frame, false); return RNull.instance; } private static final class WhileRepeatingNode extends AbstractRepeatingNode { @Child private ConvertBooleanNode condition; private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile(); private final BranchProfile normalBlock = BranchProfile.create(); private final BranchProfile breakBlock = BranchProfile.create(); private final BranchProfile nextBlock = BranchProfile.create(); // only used for toString private final WhileNode whileNode; WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) { super(body); this.whileNode = whileNode; this.condition = condition; // pre-initialize the profile so that loop exits to not deoptimize conditionProfile.profile(false); } @Override public boolean executeRepeating(VirtualFrame frame) { try { if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) { body.voidExecute(frame); normalBlock.enter(); return true; } else { return false; } } catch (BreakException e) { breakBlock.enter(); return false; } catch (NextException e) { nextBlock.enter(); return true; } } @Override public String toString() { return whileNode.toString(); } } @Override public RSyntaxElement[] getSyntaxArguments() { WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode(); return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()}; } @Override public ArgumentsSignature getSyntaxSignature() { return ArgumentsSignature.empty(2); } }
blob data class, long method t t f data class, long method blob 0 15008 https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/control/WhileNode.java/#L42-L114 1 2596 15008
1454  {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; }
long method long method, data class t t t  data class   0 11007 https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 1 1454 11007
917 {"answer": "YES I found bad smells, the bad smells are: 1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
abstract class RTFParser extends AbstractFilter { /** The current RTF group nesting level. */ public int level; private int state; private StringBuffer currentCharacters; private String pendingKeyword; // where keywords go while we // read their parameters private int pendingCharacter; // for the \'xx construct private long binaryBytesLeft; // in a \bin blob? ByteArrayOutputStream binaryBuf; private boolean[] savedSpecials; /** A stream to which to write warnings and debugging information * while parsing. This is set to System.out to log * any anomalous information to stdout. */ protected PrintStream warnings; // value for the 'state' variable private final int S_text = 0; // reading random text private final int S_backslashed = 1; // read a backslash, waiting for next private final int S_token = 2; // reading a multicharacter token private final int S_parameter = 3; // reading a token's parameter private final int S_aftertick = 4; // after reading \' private final int S_aftertickc = 5; // after reading \'x private final int S_inblob = 6; // in a \bin blob /** Implemented by subclasses to interpret a parameter-less RTF keyword. * The keyword is passed without the leading '/' or any delimiting * whitespace. */ public abstract boolean handleKeyword(String keyword); /** Implemented by subclasses to interpret a keyword with a parameter. * @param keyword The keyword, as with handleKeyword(String). * @param parameter The parameter following the keyword. */ public abstract boolean handleKeyword(String keyword, int parameter); /** Implemented by subclasses to interpret text from the RTF stream. */ public abstract void handleText(String text); public void handleText(char ch) { handleText(String.valueOf(ch)); } /** Implemented by subclasses to handle the contents of the \bin keyword. */ public abstract void handleBinaryBlob(byte[] data); /** Implemented by subclasses to react to an increase * in the nesting level. */ public abstract void begingroup(); /** Implemented by subclasses to react to the end of a group. */ public abstract void endgroup(); // table of non-text characters in rtf static final boolean[] rtfSpecialsTable; static { rtfSpecialsTable = noSpecialsTable.clone(); rtfSpecialsTable['\n'] = true; rtfSpecialsTable['\r'] = true; rtfSpecialsTable['{'] = true; rtfSpecialsTable['}'] = true; rtfSpecialsTable['\\'] = true; } public RTFParser() { currentCharacters = new StringBuffer(); state = S_text; pendingKeyword = null; level = 0; //warnings = System.out; specialsTable = rtfSpecialsTable; } // TODO: Handle wrapup at end of file correctly. public void writeSpecial(int b) throws IOException { write((char)b); } protected void warning(String s) { if (warnings != null) { warnings.println(s); } } public void write(String s) throws IOException { if (state != S_text) { int index = 0; int length = s.length(); while(index < length && state != S_text) { write(s.charAt(index)); index ++; } if(index >= length) return; s = s.substring(index); } if (currentCharacters.length() > 0) currentCharacters.append(s); else handleText(s); } @SuppressWarnings("fallthrough") public void write(char ch) throws IOException { boolean ok; switch (state) { case S_text: if (ch == '\n' || ch == '\r') { break; // unadorned newlines are ignored } else if (ch == '{') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } level ++; begingroup(); } else if(ch == '}') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } if (level == 0) throw new IOException("Too many close-groups in RTF text"); endgroup(); level --; } else if(ch == '\\') { if (currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } state = S_backslashed; } else { currentCharacters.append(ch); } break; case S_backslashed: if (ch == '\'') { state = S_aftertick; break; } if (!Character.isLetter(ch)) { char[] newstring = new char[1]; newstring[0] = ch; if (!handleKeyword(new String(newstring))) { warning("Unknown keyword: " + newstring + " (" + (byte)ch + ")"); } state = S_text; pendingKeyword = null; /* currentCharacters is already an empty stringBuffer */ break; } state = S_token; /* FALL THROUGH */ case S_token: if (Character.isLetter(ch)) { currentCharacters.append(ch); } else { pendingKeyword = currentCharacters.toString(); currentCharacters = new StringBuffer(); // Parameter following? if (Character.isDigit(ch) || (ch == '-')) { state = S_parameter; currentCharacters.append(ch); } else { ok = handleKeyword(pendingKeyword); if (!ok) warning("Unknown keyword: " + pendingKeyword); pendingKeyword = null; state = S_text; // Non-space delimiters get included in the text if (!Character.isWhitespace(ch)) write(ch); } } break; case S_parameter: if (Character.isDigit(ch)) { currentCharacters.append(ch); } else { /* TODO: Test correct behavior of \bin keyword */ if (pendingKeyword.equals("bin")) { /* magic layer-breaking kwd */ long parameter = Long.parseLong(currentCharacters.toString()); pendingKeyword = null; state = S_inblob; binaryBytesLeft = parameter; if (binaryBytesLeft > Integer.MAX_VALUE) binaryBuf = new ByteArrayOutputStream(Integer.MAX_VALUE); else binaryBuf = new ByteArrayOutputStream((int)binaryBytesLeft); savedSpecials = specialsTable; specialsTable = allSpecialsTable; break; } int parameter = Integer.parseInt(currentCharacters.toString()); ok = handleKeyword(pendingKeyword, parameter); if (!ok) warning("Unknown keyword: " + pendingKeyword + " (param " + currentCharacters + ")"); pendingKeyword = null; currentCharacters = new StringBuffer(); state = S_text; // Delimiters here are interpreted as text too if (!Character.isWhitespace(ch)) write(ch); } break; case S_aftertick: if (Character.digit(ch, 16) == -1) state = S_text; else { pendingCharacter = Character.digit(ch, 16); state = S_aftertickc; } break; case S_aftertickc: state = S_text; if (Character.digit(ch, 16) != -1) { pendingCharacter = pendingCharacter * 16 + Character.digit(ch, 16); ch = translationTable[pendingCharacter]; if (ch != 0) handleText(ch); } break; case S_inblob: binaryBuf.write(ch); binaryBytesLeft --; if (binaryBytesLeft == 0) { state = S_text; specialsTable = savedSpecials; savedSpecials = null; handleBinaryBlob(binaryBuf.toByteArray()); binaryBuf = null; } } } /** Flushes any buffered but not yet written characters. * Subclasses which override this method should call this * method before flushing * any of their own buffers. */ public void flush() throws IOException { super.flush(); if (state == S_text && currentCharacters.length() > 0) { handleText(currentCharacters.toString()); currentCharacters = new StringBuffer(); } } /** Closes the parser. Currently, this simply does a flush(), * followed by some minimal consistency checks. */ public void close() throws IOException { flush(); if (state != S_text || level > 0) { warning("Truncated RTF file."); /* TODO: any sane way to handle termination in a non-S_text state? */ /* probably not */ /* this will cause subclasses to behave more reasonably some of the time */ while (level > 0) { endgroup(); level --; } } super.close(); } }
blob 1. data class t t f 1. data class blob 0 8249 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/rtf/RTFParser.java/#L41-L334 1 917 8249
2240 {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("serial") public class ConnectDialog extends InternalDialog implements DocumentListener, FocusListener, ItemListener, ListSelectionListener, KeyListener { private static final int COL_NAME = 0; private static final int COL_PID = 1; JConsole jConsole; JTextField userNameTF, passwordTF; JRadioButton localRadioButton, remoteRadioButton; JLabel localMessageLabel, remoteMessageLabel; JTextField remoteTF; JButton connectButton, cancelButton; JPanel radioButtonPanel; private Icon mastheadIcon = new MastheadIcon(Messages.CONNECT_DIALOG_MASTHEAD_TITLE); private Color hintTextColor, disabledTableCellColor; // The table of managed VM (local process) JTable vmTable; ManagedVmTableModel vmModel = null; JScrollPane localTableScrollPane = null; private Action connectAction, cancelAction; public ConnectDialog(JConsole jConsole) { super(jConsole, Messages.CONNECT_DIALOG_TITLE, true); this.jConsole = jConsole; setAccessibleDescription(this, Messages.CONNECT_DIALOG_ACCESSIBLE_DESCRIPTION); setDefaultCloseOperation(HIDE_ON_CLOSE); setResizable(false); Container cp = (JComponent)getContentPane(); radioButtonPanel = new JPanel(new BorderLayout(0, 12)); radioButtonPanel.setBorder(new EmptyBorder(6, 12, 12, 12)); ButtonGroup radioButtonGroup = new ButtonGroup(); JPanel bottomPanel = new JPanel(new BorderLayout()); statusBar = new JLabel(" ", JLabel.CENTER); setAccessibleName(statusBar, Messages.CONNECT_DIALOG_STATUS_BAR_ACCESSIBLE_NAME); Font normalLabelFont = statusBar.getFont(); Font boldLabelFont = normalLabelFont.deriveFont(Font.BOLD); Font smallLabelFont = normalLabelFont.deriveFont(normalLabelFont.getSize2D() - 1); JLabel mastheadLabel = new JLabel(mastheadIcon); setAccessibleName(mastheadLabel, Messages.CONNECT_DIALOG_MASTHEAD_ACCESSIBLE_NAME); cp.add(mastheadLabel, NORTH); cp.add(radioButtonPanel, CENTER); cp.add(bottomPanel, SOUTH); createActions(); remoteTF = new JTextField(); remoteTF.addActionListener(connectAction); remoteTF.getDocument().addDocumentListener(this); remoteTF.addFocusListener(this); remoteTF.setPreferredSize(remoteTF.getPreferredSize()); setAccessibleName(remoteTF, Messages.REMOTE_PROCESS_TEXT_FIELD_ACCESSIBLE_NAME); // // If the VM supports the local attach mechanism (is: Sun // implementation) then the Local Process panel is created. // if (JConsole.isLocalAttachAvailable()) { vmModel = new ManagedVmTableModel(); vmTable = new LocalTabJTable(vmModel); vmTable.setSelectionMode(SINGLE_SELECTION); vmTable.setPreferredScrollableViewportSize(new Dimension(400, 250)); vmTable.setColumnSelectionAllowed(false); vmTable.addFocusListener(this); vmTable.getSelectionModel().addListSelectionListener(this); TableColumnModel columnModel = vmTable.getColumnModel(); TableColumn pidColumn = columnModel.getColumn(COL_PID); pidColumn.setMaxWidth(getLabelWidth("9999999")); pidColumn.setResizable(false); TableColumn cmdLineColumn = columnModel.getColumn(COL_NAME); cmdLineColumn.setResizable(false); localRadioButton = new JRadioButton(Messages.LOCAL_PROCESS_COLON); localRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.LOCAL_PROCESS_COLON)); localRadioButton.setFont(boldLabelFont); localRadioButton.addItemListener(this); radioButtonGroup.add(localRadioButton); JPanel localPanel = new JPanel(new BorderLayout()); JPanel localTablePanel = new JPanel(new BorderLayout()); radioButtonPanel.add(localPanel, NORTH); localPanel.add(localRadioButton, NORTH); localPanel.add(new Padder(localRadioButton), LINE_START); localPanel.add(localTablePanel, CENTER); localTableScrollPane = new JScrollPane(vmTable); localTablePanel.add(localTableScrollPane, NORTH); localMessageLabel = new JLabel(" "); localMessageLabel.setFont(smallLabelFont); localMessageLabel.setForeground(hintTextColor); localTablePanel.add(localMessageLabel, SOUTH); } remoteRadioButton = new JRadioButton(Messages.REMOTE_PROCESS_COLON); remoteRadioButton.setMnemonic(Resources.getMnemonicInt(Messages.REMOTE_PROCESS_COLON)); remoteRadioButton.setFont(boldLabelFont); radioButtonGroup.add(remoteRadioButton); JPanel remotePanel = new JPanel(new BorderLayout()); if (localRadioButton != null) { remotePanel.add(remoteRadioButton, NORTH); remotePanel.add(new Padder(remoteRadioButton), LINE_START); Action nextRadioButtonAction = new AbstractAction("nextRadioButton") { public void actionPerformed(ActionEvent ev) { JRadioButton rb = (ev.getSource() == localRadioButton) ? remoteRadioButton : localRadioButton; rb.doClick(); rb.requestFocus(); } }; localRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); remoteRadioButton.getActionMap().put("nextRadioButton", nextRadioButtonAction); localRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextRadioButton"); remoteRadioButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "nextRadioButton"); } else { JLabel remoteLabel = new JLabel(remoteRadioButton.getText()); remoteLabel.setFont(boldLabelFont); remotePanel.add(remoteLabel, NORTH); } radioButtonPanel.add(remotePanel, SOUTH); JPanel remoteTFPanel = new JPanel(new BorderLayout()); remotePanel.add(remoteTFPanel, CENTER); remoteTFPanel.add(remoteTF, NORTH); remoteMessageLabel = new JLabel("" + Messages.REMOTE_TF_USAGE + ""); remoteMessageLabel.setFont(smallLabelFont); remoteMessageLabel.setForeground(hintTextColor); remoteTFPanel.add(remoteMessageLabel, CENTER); JPanel userPwdPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); userPwdPanel.setBorder(new EmptyBorder(12, 0, 0, 0)); // top padding int tfWidth = JConsole.IS_WIN ? 12 : 8; userNameTF = new JTextField(tfWidth); userNameTF.addActionListener(connectAction); userNameTF.getDocument().addDocumentListener(this); userNameTF.addFocusListener(this); setAccessibleName(userNameTF, Messages.USERNAME_ACCESSIBLE_NAME); LabeledComponent lc; lc = new LabeledComponent(Messages.USERNAME_COLON_, Resources.getMnemonicInt(Messages.USERNAME_COLON_), userNameTF); lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); passwordTF = new JPasswordField(tfWidth); // Heights differ, so fix here passwordTF.setPreferredSize(userNameTF.getPreferredSize()); passwordTF.addActionListener(connectAction); passwordTF.getDocument().addDocumentListener(this); passwordTF.addFocusListener(this); setAccessibleName(passwordTF, Messages.PASSWORD_ACCESSIBLE_NAME); lc = new LabeledComponent(Messages.PASSWORD_COLON_, Resources.getMnemonicInt(Messages.PASSWORD_COLON_), passwordTF); lc.setBorder(new EmptyBorder(0, 12, 0, 0)); // Left padding lc.label.setFont(boldLabelFont); userPwdPanel.add(lc); remoteTFPanel.add(userPwdPanel, SOUTH); String connectButtonToolTipText = Messages.CONNECT_DIALOG_CONNECT_BUTTON_TOOLTIP; connectButton = new JButton(connectAction); connectButton.setToolTipText(connectButtonToolTipText); cancelButton = new JButton(cancelAction); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonPanel.setBorder(new EmptyBorder(12, 12, 2, 12)); if (JConsole.IS_GTK) { buttonPanel.add(cancelButton); buttonPanel.add(connectButton); } else { buttonPanel.add(connectButton); buttonPanel.add(cancelButton); } bottomPanel.add(buttonPanel, NORTH); bottomPanel.add(statusBar, SOUTH); updateButtonStates(); Utilities.updateTransparency(this); } public void revalidate() { // Adjust some colors Color disabledForeground = UIManager.getColor("Label.disabledForeground"); if (disabledForeground == null) { // fall back for Nimbus that doesn't support 'Label.disabledForeground' disabledForeground = UIManager.getColor("Label.disabledText"); } hintTextColor = ensureContrast(disabledForeground, UIManager.getColor("Panel.background")); disabledTableCellColor = ensureContrast(new Color(0x808080), UIManager.getColor("Table.background")); if (remoteMessageLabel != null) { remoteMessageLabel.setForeground(hintTextColor); // Update html color setting String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); remoteMessageLabel.setText("" + Messages.REMOTE_TF_USAGE); } if (localMessageLabel != null) { localMessageLabel.setForeground(hintTextColor); // Update html color setting valueChanged(null); } super.revalidate(); } private void createActions() { connectAction = new AbstractAction(Messages.CONNECT) { /* init */ { putValue(Action.MNEMONIC_KEY, Resources.getMnemonicInt(Messages.CONNECT)); } public void actionPerformed(ActionEvent ev) { if (!isEnabled() || !isVisible()) { return; } setVisible(false); statusBar.setText(""); if (remoteRadioButton.isSelected()) { String txt = remoteTF.getText().trim(); String userName = userNameTF.getText().trim(); userName = userName.isEmpty() ? null : userName; String password = passwordTF.getText(); password = password.isEmpty() ? null : password; try { if (txt.startsWith(JConsole.ROOT_URL)) { String url = txt; jConsole.addUrl(url, userName, password, false); remoteTF.setText(JConsole.ROOT_URL); return; } else { String host = remoteTF.getText().trim(); String port = "0"; int index = host.lastIndexOf(':'); if (index >= 0) { port = host.substring(index + 1); host = host.substring(0, index); } if (host.length() > 0 && port.length() > 0) { int p = Integer.parseInt(port.trim()); jConsole.addHost(host, p, userName, password); remoteTF.setText(""); userNameTF.setText(""); passwordTF.setText(""); return; } } } catch (Exception ex) { statusBar.setText(ex.toString()); } setVisible(true); } else if (localRadioButton != null && localRadioButton.isSelected()) { // Try to connect to selected VM. If a connection // cannot be established for some reason (the process has // terminated for example) then keep the dialog open showing // the connect error. // int row = vmTable.getSelectedRow(); if (row >= 0) { jConsole.addVmid(vmModel.vmAt(row)); } refresh(); } } }; cancelAction = new AbstractAction(Messages.CANCEL) { public void actionPerformed(ActionEvent ev) { setVisible(false); statusBar.setText(""); } }; } // a label used solely for calculating the width private static JLabel tmpLabel = new JLabel(); public static int getLabelWidth(String text) { tmpLabel.setText(text); return (int) tmpLabel.getPreferredSize().getWidth() + 1; } private class LocalTabJTable extends JTable { ManagedVmTableModel vmModel; Border rendererBorder = new EmptyBorder(0, 6, 0, 6); public LocalTabJTable(ManagedVmTableModel model) { super(model); this.vmModel = model; // Remove vertical lines, expect for GTK L&F. // (because GTK doesn't show header dividers) if (!JConsole.IS_GTK) { setShowVerticalLines(false); setIntercellSpacing(new Dimension(0, 1)); } // Double-click handler addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { connectButton.doClick(); } } }); // Enter should call default action getActionMap().put("connect", connectAction); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "connect"); } public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (realColumnIndex == COL_NAME) { LocalVirtualMachine vmd = vmModel.vmAt(rowIndex); tip = vmd.toString(); } return tip; } public TableCellRenderer getCellRenderer(int row, int column) { return new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable() && !lvm.isAttachable()) { comp.setForeground(disabledTableCellColor); } } if (comp instanceof JLabel) { JLabel label = (JLabel)comp; label.setBorder(rendererBorder); if (value instanceof Integer) { label.setHorizontalAlignment(JLabel.RIGHT); } } return comp; } }; } } public void setConnectionParameters(String url, String host, int port, String userName, String password, String msg) { if ((url != null && url.length() > 0) || (host != null && host.length() > 0 && port > 0)) { remoteRadioButton.setSelected(true); if (url != null && url.length() > 0) { remoteTF.setText(url); } else { remoteTF.setText(host+":"+port); } userNameTF.setText((userName != null) ? userName : ""); passwordTF.setText((password != null) ? password : ""); statusBar.setText((msg != null) ? msg : ""); if (getPreferredSize().width > getWidth()) { pack(); } remoteTF.requestFocus(); remoteTF.selectAll(); } } public void itemStateChanged(ItemEvent ev) { if (!localRadioButton.isSelected()) { vmTable.getSelectionModel().clearSelection(); } updateButtonStates(); } private void updateButtonStates() { boolean connectEnabled = false; if (remoteRadioButton.isSelected()) { connectEnabled = JConsole.isValidRemoteString(remoteTF.getText()); } else if (localRadioButton != null && localRadioButton.isSelected()) { int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); connectEnabled = (lvm.isManageable() || lvm.isAttachable()); } } connectAction.setEnabled(connectEnabled); } public void insertUpdate(DocumentEvent e) { updateButtonStates(); } public void removeUpdate(DocumentEvent e) { updateButtonStates(); } public void changedUpdate(DocumentEvent e) { updateButtonStates(); } public void focusGained(FocusEvent e) { Object source = e.getSource(); Component opposite = e.getOppositeComponent(); if (!e.isTemporary() && source instanceof JTextField && opposite instanceof JComponent && SwingUtilities.getRootPane(opposite) == getRootPane()) { ((JTextField)source).selectAll(); } if (source == remoteTF) { remoteRadioButton.setSelected(true); } else if (source == vmTable) { localRadioButton.setSelected(true); if (vmModel.getRowCount() == 1) { // if there's only one process then select the row vmTable.setRowSelectionInterval(0, 0); } } updateButtonStates(); } public void focusLost(FocusEvent e) { } public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (c == KeyEvent.VK_ESCAPE) { setVisible(false); } else if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) { getToolkit().beep(); e.consume(); } } public void setVisible(boolean b) { boolean wasVisible = isVisible(); super.setVisible(b); if (b && !wasVisible) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (remoteRadioButton.isSelected()) { remoteTF.requestFocus(); remoteTF.selectAll(); } } }); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } // ListSelectionListener interface public void valueChanged(ListSelectionEvent e) { updateButtonStates(); String labelText = " "; // Non-empty to reserve vertical space int row = vmTable.getSelectedRow(); if (row >= 0) { LocalVirtualMachine lvm = vmModel.vmAt(row); if (!lvm.isManageable()) { if (lvm.isAttachable()) { labelText = Messages.MANAGEMENT_WILL_BE_ENABLED; } else { labelText = Messages.MANAGEMENT_NOT_ENABLED; } } } String colorStr = String.format("%06x", hintTextColor.getRGB() & 0xFFFFFF); localMessageLabel.setText("" + labelText); } // ---- // Refresh the list of managed VMs public void refresh() { if (vmModel != null) { // Remember selection LocalVirtualMachine selected = null; int row = vmTable.getSelectedRow(); if (row >= 0) { selected = vmModel.vmAt(row); } vmModel.refresh(); int selectRow = -1; int n = vmModel.getRowCount(); if (selected != null) { for (int i = 0; i < n; i++) { LocalVirtualMachine lvm = vmModel.vmAt(i); if (selected.vmid() == lvm.vmid() && selected.toString().equals(lvm.toString())) { selectRow = i; break; } } } if (selectRow > -1) { vmTable.setRowSelectionInterval(selectRow, selectRow); } else { vmTable.getSelectionModel().clearSelection(); } Dimension dim = vmTable.getPreferredSize(); // Tricky. Reduce height by one to avoid double line at bottom, // but that causes a scroll bar to appear, so remove it. dim.height = Math.min(dim.height-1, 100); localTableScrollPane.setVerticalScrollBarPolicy((dim.height < 100) ? JScrollPane.VERTICAL_SCROLLBAR_NEVER : JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); localTableScrollPane.getViewport().setMinimumSize(dim); localTableScrollPane.getViewport().setPreferredSize(dim); } pack(); setLocationRelativeTo(jConsole); } // Represents the list of managed VMs as a tabular data model. private static class ManagedVmTableModel extends AbstractTableModel { private static String[] columnNames = { Messages.COLUMN_NAME, Messages.COLUMN_PID, }; private List vmList; public int getColumnCount() { return columnNames.length; } public String getColumnName(int col) { return columnNames[col]; } public synchronized int getRowCount() { return vmList.size(); } public synchronized Object getValueAt(int row, int col) { assert col >= 0 && col <= columnNames.length; LocalVirtualMachine vm = vmList.get(row); switch (col) { case COL_NAME: return vm.displayName(); case COL_PID: return vm.vmid(); default: return null; } } public Class getColumnClass(int column) { switch (column) { case COL_NAME: return String.class; case COL_PID: return Integer.class; default: return super.getColumnClass(column); } } public ManagedVmTableModel() { refresh(); } public synchronized LocalVirtualMachine vmAt(int pos) { return vmList.get(pos); } public synchronized void refresh() { Map map = LocalVirtualMachine.getAllVirtualMachines(); vmList = new ArrayList(); vmList.addAll(map.values()); // data has changed fireTableDataChanged(); } } // A blank component that takes up as much space as the // button part of a JRadioButton. private static class Padder extends JPanel { JRadioButton radioButton; Padder(JRadioButton radioButton) { this.radioButton = radioButton; setAccessibleName(this, Messages.BLANK); } public Dimension getPreferredSize() { Rectangle r = getTextRectangle(radioButton); int w = (r != null && r.x > 8) ? r.x : 22; return new Dimension(w, 0); } private static Rectangle getTextRectangle(AbstractButton button) { String text = button.getText(); Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon(); if (icon == null && button.getUI() instanceof BasicRadioButtonUI) { icon = ((BasicRadioButtonUI)button.getUI()).getDefaultIcon(); } if ((icon == null) && (text == null)) { return null; } Rectangle paintIconR = new Rectangle(); Rectangle paintTextR = new Rectangle(); Rectangle paintViewR = new Rectangle(); Insets paintViewInsets = new Insets(0, 0, 0, 0); paintViewInsets = button.getInsets(paintViewInsets); paintViewR.x = paintViewInsets.left; paintViewR.y = paintViewInsets.top; paintViewR.width = button.getWidth() - (paintViewInsets.left + paintViewInsets.right); paintViewR.height = button.getHeight() - (paintViewInsets.top + paintViewInsets.bottom); Graphics g = button.getGraphics(); if (g == null) { return null; } SwingUtilities.layoutCompoundLabel(button, g.getFontMetrics(), text, icon, button.getVerticalAlignment(), button.getHorizontalAlignment(), button.getVerticalTextPosition(), button.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, button.getIconTextGap()); return paintTextR; } } }
blob data class t t f data class blob 0 13619 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.jconsole/share/classes/sun/tools/jconsole/ConnectDialog.java/#L45-L768 1 2240 13619
1822  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class
blob Data Class, Long Method t f f Data Class, Long Method blob 0 12100 https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 1 1822 12100
1057 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SparkCubingMerge extends AbstractApplication implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(SparkCubingMerge.class); public static final Option OPTION_CUBE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_CUBE_NAME).hasArg() .isRequired(true).withDescription("Cube Name").create(BatchConstants.ARG_CUBE_NAME); public static final Option OPTION_SEGMENT_ID = OptionBuilder.withArgName("segment").hasArg().isRequired(true) .withDescription("Cube Segment Id").create("segmentId"); public static final Option OPTION_META_URL = OptionBuilder.withArgName("metaUrl").hasArg().isRequired(true) .withDescription("HDFS metadata url").create("metaUrl"); public static final Option OPTION_OUTPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg() .isRequired(true).withDescription("HFile output path").create(BatchConstants.ARG_OUTPUT); public static final Option OPTION_INPUT_PATH = OptionBuilder.withArgName(BatchConstants.ARG_INPUT).hasArg() .isRequired(true).withDescription("Cuboid files PATH").create(BatchConstants.ARG_INPUT); private Options options; private String cubeName; private String metaUrl; public SparkCubingMerge() { options = new Options(); options.addOption(OPTION_META_URL); options.addOption(OPTION_CUBE_NAME); options.addOption(OPTION_SEGMENT_ID); options.addOption(OPTION_INPUT_PATH); options.addOption(OPTION_OUTPUT_PATH); } @Override protected Options getOptions() { return options; } @Override protected void execute(OptionsHelper optionsHelper) throws Exception { this.metaUrl = optionsHelper.getOptionValue(OPTION_META_URL); this.cubeName = optionsHelper.getOptionValue(OPTION_CUBE_NAME); final String inputPath = optionsHelper.getOptionValue(OPTION_INPUT_PATH); final String segmentId = optionsHelper.getOptionValue(OPTION_SEGMENT_ID); final String outputPath = optionsHelper.getOptionValue(OPTION_OUTPUT_PATH); Class[] kryoClassArray = new Class[] { Class.forName("scala.reflect.ClassTag$$anon$1") }; SparkConf conf = new SparkConf().setAppName("Merge segments for cube:" + cubeName + ", segment " + segmentId); //serialization conf conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer"); conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator"); conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray); try (JavaSparkContext sc = new JavaSparkContext(conf)) { SparkUtil.modifySparkHadoopConfiguration(sc.sc()); // set dfs.replication=2 and enable compress KylinSparkJobListener jobListener = new KylinSparkJobListener(); sc.sc().addSparkListener(jobListener); HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(outputPath)); final SerializableConfiguration sConf = new SerializableConfiguration(sc.hadoopConfiguration()); final KylinConfig envConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); final CubeInstance cubeInstance = CubeManager.getInstance(envConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(envConfig).getCubeDesc(cubeInstance.getDescName()); final CubeSegment cubeSegment = cubeInstance.getSegmentById(segmentId); final CubeStatsReader cubeStatsReader = new CubeStatsReader(cubeSegment, envConfig); logger.info("Input path: {}", inputPath); logger.info("Output path: {}", outputPath); final Job job = Job.getInstance(sConf.get()); SparkUtil.setHadoopConfForCuboid(job, cubeSegment, metaUrl); final MeasureAggregators aggregators = new MeasureAggregators(cubeDesc.getMeasures()); final Function2 reduceFunction = new Function2() { @Override public Object[] call(Object[] input1, Object[] input2) throws Exception { Object[] measureObjs = new Object[input1.length]; aggregators.aggregate(input1, input2, measureObjs); return measureObjs; } }; final PairFunction convertTextFunction = new PairFunction, org.apache.hadoop.io.Text, org.apache.hadoop.io.Text>() { private transient volatile boolean initialized = false; BufferedMeasureCodec codec; @Override public Tuple2 call(Tuple2 tuple2) throws Exception { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { synchronized (SparkCubingMerge.class) { if (initialized == false) { KylinConfig kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(sConf, metaUrl); try (KylinConfig.SetAndUnsetThreadLocalConfig autoUnset = KylinConfig .setAndUnsetThreadLocalConfig(kylinConfig)) { CubeDesc desc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cubeName); codec = new BufferedMeasureCodec(desc.getMeasures()); initialized = true; } } } } } } ByteBuffer valueBuf = codec.encode(tuple2._2()); byte[] encodedBytes = new byte[valueBuf.position()]; System.arraycopy(valueBuf.array(), 0, encodedBytes, 0, valueBuf.position()); return new Tuple2<>(tuple2._1(), new org.apache.hadoop.io.Text(encodedBytes)); } }; final int totalLevels = cubeSegment.getCuboidScheduler().getBuildLevel(); final String[] inputFolders = StringSplitter.split(inputPath, ","); FileSystem fs = HadoopUtil.getWorkingFileSystem(); boolean isLegacyMode = false; for (String inputFolder : inputFolders) { Path baseCuboidPath = new Path(BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(inputFolder, 0)); if (fs.exists(baseCuboidPath) == false) { // doesn't exist sub folder, that means the merged cuboid in one folder (not by layer) isLegacyMode = true; break; } } if (isLegacyMode == true) { // merge all layer's cuboid at once, this might be hard for Spark List> mergingSegs = Lists.newArrayListWithExpectedSize(inputFolders.length); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; JavaPairRDD segRdd = SparkUtil.parseInputPath(path, fs, sc, Text.class, Text.class); CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateTotalPartitionNum(cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } else { // merge by layer for (int level = 0; level <= totalLevels; level++) { List> mergingSegs = Lists.newArrayList(); for (int i = 0; i < inputFolders.length; i++) { String path = inputFolders[i]; CubeSegment sourceSegment = findSourceSegment(path, cubeInstance); final String cuboidInputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(path, level); JavaPairRDD segRdd = sc.sequenceFile(cuboidInputPath, Text.class, Text.class); // re-encode with new dictionaries JavaPairRDD newEcoddedRdd = segRdd.mapToPair(new ReEncodeCuboidFunction(cubeName, sourceSegment.getUuid(), cubeSegment.getUuid(), metaUrl, sConf)); mergingSegs.add(newEcoddedRdd); } final String cuboidOutputPath = BatchCubingJobBuilder2.getCuboidOutputPathsByLevel(outputPath, level); FileOutputFormat.setOutputPath(job, new Path(cuboidOutputPath)); sc.union(mergingSegs.toArray(new JavaPairRDD[mergingSegs.size()])) .reduceByKey(reduceFunction, SparkUtil.estimateLayerPartitionNum(level, cubeStatsReader, envConfig)) .mapToPair(convertTextFunction).saveAsNewAPIHadoopDataset(job.getConfiguration()); } } // output the data size to console, job engine will parse and save the metric // please note: this mechanism won't work when spark.submit.deployMode=cluster logger.info("HDFS: Number of bytes written={}", jobListener.metrics.getBytesWritten()); } } static class ReEncodeCuboidFunction implements PairFunction, Text, Object[]> { private transient volatile boolean initialized = false; private String cubeName; private String sourceSegmentId; private String mergedSegmentId; private String metaUrl; private SerializableConfiguration conf; private transient KylinConfig kylinConfig; private transient SegmentReEncoder segmentReEncoder = null; ReEncodeCuboidFunction(String cubeName, String sourceSegmentId, String mergedSegmentId, String metaUrl, SerializableConfiguration conf) { this.cubeName = cubeName; this.sourceSegmentId = sourceSegmentId; this.mergedSegmentId = mergedSegmentId; this.metaUrl = metaUrl; this.conf = conf; } private void init() { this.kylinConfig = AbstractHadoopJob.loadKylinConfigFromHdfs(conf, metaUrl); final CubeInstance cube = CubeManager.getInstance(kylinConfig).getCube(cubeName); final CubeDesc cubeDesc = CubeDescManager.getInstance(kylinConfig).getCubeDesc(cube.getDescName()); final CubeSegment sourceSeg = cube.getSegmentById(sourceSegmentId); final CubeSegment mergedSeg = cube.getSegmentById(mergedSegmentId); this.segmentReEncoder = new SegmentReEncoder(cubeDesc, sourceSeg, mergedSeg, kylinConfig); } @Override public Tuple2 call(Tuple2 textTextTuple2) throws Exception { if (initialized == false) { synchronized (ReEncodeCuboidFunction.class) { if (initialized == false) { init(); initialized = true; } } } Pair encodedPair = segmentReEncoder.reEncode2(textTextTuple2._1, textTextTuple2._2); return new Tuple2(encodedPair.getFirst(), encodedPair.getSecond()); } } private CubeSegment findSourceSegment(String filePath, CubeInstance cube) { String jobID = JobBuilderSupport.extractJobIDFromPath(filePath); return CubeInstance.findSegmentWithJobId(jobID, cube); } }
blob long method, data class t t f long method, data class blob 0 9518 https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/engine-spark/src/main/java/org/apache/kylin/engine/spark/SparkCubingMerge.java/#L64-L286 1 1057 9518
5515   YES I found bad smells the bad smells are: Long method, Feature envy, Data class The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } }
long method  Long method, Feature envy, Data class t f t  Feature envy, Data class   0 4260 https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 1 5515 4260
2274 {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; }
long method long method, data class t t t  data class   0 13771 https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 1 2274 13771
523  { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } }
blob 'Long Method', 'Data Class' t t f {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',D,a,t,a," ",C,l,a,s,s,'} {',o,n,g," ",M,t,h,o,d,',","," ",',D,t," ",C,'} 0 5426 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 1 523 5426
437  {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Builder(float k1, float b) { this.similarity = new BM25Similarity(k1, b); }
feature envy data class t t f data class feature envy 0 4292 https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L78-L80 1 437 4292
590 {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; }
long method long method, data class t t t  data class   0 5890 https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 1 590 5890
3774 { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Feature Envy", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class UploadFileViewImpl extends Window implements UploadFileView { public interface UploadFileViewBinder extends UiBinder {} private final AgentURLModifier agentURLModifier; Button btnCancel; Button btnUpload; @UiField FormPanel submitForm; @UiField CheckBox overwrite; @UiField FlowPanel uploadPanel; FileUpload file; ActionDelegate delegate; /** Create view. */ @Inject public UploadFileViewImpl( UploadFileViewBinder uploadFileViewBinder, CoreLocalizationConstant locale, AgentURLModifier agentURLModifier) { this.setTitle(locale.uploadFileTitle()); setWidget(uploadFileViewBinder.createAndBindUi(this)); bind(); btnCancel = addFooterButton( locale.cancel(), "file-uploadFile-cancel", event -> delegate.onCancelClicked()); btnUpload = addFooterButton( locale.uploadButton(), "file-uploadFile-upload", event -> delegate.onUploadClicked(), true); this.agentURLModifier = agentURLModifier; } /** Bind handlers. */ private void bind() { submitForm.addSubmitCompleteHandler(event -> delegate.onSubmitComplete(event.getResults())); } /** {@inheritDoc} */ @Override public void showDialog() { show(); } @Override protected void onShow() { addFile(); } /** {@inheritDoc} */ @Override public void closeDialog() { hide(); } @Override protected void onHide() { btnUpload.setEnabled(false); overwrite.setValue(false); uploadPanel.remove(file); } /** {@inheritDoc} */ @Override public void setDelegate(ActionDelegate delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public void setEnabledUploadButton(boolean enabled) { btnUpload.setEnabled(enabled); } /** {@inheritDoc} */ @Override public void setEncoding(@NotNull String encodingType) { submitForm.setEncoding(encodingType); } /** {@inheritDoc} */ @Override public void setAction(@NotNull String url) { submitForm.setAction(agentURLModifier.modify(url)); submitForm.setMethod(FormPanel.METHOD_POST); } /** {@inheritDoc} */ @Override public void submit() { overwrite.setFormValue(overwrite.getValue().toString()); submitForm.submit(); btnUpload.setEnabled(false); } /** {@inheritDoc} */ @Override @NotNull public String getFileName() { String fileName = file.getFilename(); if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { return fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; } /** {@inheritDoc} */ @Override public boolean isOverwriteFileSelected() { return overwrite.getValue(); } private void addFile() { file = new FileUpload(); file.setHeight("22px"); file.setWidth("100%"); file.setName("file"); file.ensureDebugId("file-uploadFile-ChooseFile"); file.addChangeHandler(event -> delegate.onFileNameChanged()); uploadPanel.insert(file, 0); } }
blob data class, feature envy, long method t t f data class, feature envy, long method blob 0 9458 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/upload/file/UploadFileViewImpl.java/#L33-L164 1 3774 9458
3 {"response": "YES I found bad smells","detected_bad_smells":[ "1. Long Method", "2. Data Class" ]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 554 https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 1 3 554
692      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } }
feature envy long method, data class t t f long method, data class feature envy 0 6653 https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 1 692 6653
4206 { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } }
blob data class t t f data class blob 0 11068 https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 1 4206 11068
996    { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } }
long method long method, data class t t t  data class   0 9119 https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 1 996 9119
42      { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } }
feature envy data class, long method t t f data class, long method feature envy 0 805 https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 1 42 805
4852 {"answer":"YES I found bad smells","detected_smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } }
blob long method, data class t t f long method, data class blob 0 13206 https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 1 4852 13206
255 {"result": "YES I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
final class Prefixes { /** * The SI “deca” prefix. This is the only SI prefix encoded on two letters instead than one. * It can be represented by the CJK compatibility character “㍲”, but use of those characters * is generally not recommended outside of Chinese, Japanese or Korean texts. */ private static final String DECA = "da"; /** * The SI prefixes in increasing order. The only two-letters prefix – “da” – is encoded using the JCK compatibility * character “㍲”. The Greek letter μ is repeated twice: the U+00B5 character for micro sign (this is the character * that Apache SIS uses in unit symbols) and the U+03BC character for the Greek small letter “mu” (the later is the * character that appears when decomposing JCK compatibility characters with {@link java.text.Normalizer}). * Both characters have same appearance but different values. * * For each prefix at index i, the multiplication factor is given by 10 raised to power {@code POWERS[i]}. */ private static final char[] PREFIXES = {'E','G','M','P','T','Y','Z','a','c','d','f','h','k','m','n','p','y','z','µ','μ','㍲'}; private static final byte[] POWERS = {18, 9, 6, 15, 12, 24, 21,-18, -2, -1,-15, 2, 3, -3, -9,-12,-24,-21, -6, -6, 1}; /** * The SI prefixes from smallest to largest. Power of tens go from -24 to +24 inclusive with a step of 3, * except for the addition of -2, -1, +1, +2 and the omission of 0. * * @see #symbol(double, int) */ private static final char[] ENUM = {'y','z','a','f','p','n','µ','m','c','d','㍲','h','k','M','G','T','P','E','Z','Y'}; /** * The maximal power of 1000 for the prefixes in the {@link #ENUM} array. Note that 1000⁸ = 1E+24. */ static final int MAX_POWER = 8; /** * The converters for SI prefixes, created when first needed. * * @see #converter(char) */ private static final LinearConverter[] CONVERTERS = new LinearConverter[POWERS.length]; /** * Do not allow instantiation of this class. */ private Prefixes() { } /** * Returns the converter for the given SI prefix, or {@code null} if none. * Those converters are created when first needed and cached for reuse. */ static LinearConverter converter(final char prefix) { final int i = Arrays.binarySearch(PREFIXES, prefix); if (i < 0) { return null; } synchronized (CONVERTERS) { LinearConverter c = CONVERTERS[i]; if (c == null) { final int p = POWERS[i]; final double numerator, denominator; if (p >= 0) { numerator = MathFunctions.pow10(p); denominator = 1; } else { numerator = 1; denominator = MathFunctions.pow10(-p); } c = LinearConverter.scale(numerator, denominator); CONVERTERS[i] = c; } return c; } } /** * Returns the SI prefix symbol for the given scale factor, or 0 if none. * * @param scale the scale factor. * @param power the unit power. For example if we are scaling m², then this is 2. * @return the prefix, or 0 if none. */ static char symbol(double scale, final int power) { switch (power) { case 0: return 0; case 1: break; case 2: scale = Math.sqrt(scale); break; case 3: scale = Math.cbrt(scale); break; default: scale = Math.pow(scale, 1.0/power); } final int n = Numerics.toExp10(Math.getExponent(scale)) + 1; if (AbstractConverter.epsilonEquals(MathFunctions.pow10(n), scale)) { int i = Math.abs(n); switch (i) { case 0: return 0; case 1: // Fallthrough case 2: break; default: { if (i > (MAX_POWER*3) || (i % 3) != 0) { return 0; } i = i/3 + 2; break; } } return ENUM[n >= 0 ? (MAX_POWER+1) + i : (MAX_POWER+2) - i]; } return 0; } /** * Returns the concatenation of the given prefix with the given unit symbol. */ static String concat(final char prefix, final String unit) { return (prefix == '㍲') ? DECA + unit : prefix + unit; } /** * Returns the unit for the given symbol, taking the SI prefix in account. The given string is usually a single symbol * like "km", but may be an expression like "m³" or "m/s" if the given symbol is explicitly registered as an item that * {@link Units#get(String)} recognizes. This method does not perform any arithmetic operation on {@code Unit}, * except a check for the exponent. * * @param uom a symbol compliant with the rules documented in {@link AbstractUnit#symbol}. * @return the unit for the given symbol, or {@code null} if no unit is found. */ static Unit getUnit(final String uom) { Unit unit = Units.get(uom); if (unit == null && uom.length() >= 2) { int s = 1; char prefix = uom.charAt(0); if (prefix == 'd' && uom.charAt(1) == 'a') { prefix = '㍲'; // Converse of above 'concat(char, String)' method. s = 2; // Skip "da", which we represent by '㍲'. } unit = Units.get(uom.substring(s)); if (AbstractUnit.isPrefixable(unit)) { LinearConverter c = Prefixes.converter(prefix); if (c != null) { String symbol = unit.getSymbol(); final int power = ConventionalUnit.power(symbol); if (power != 0) { if (power != 1) { c = LinearConverter.pow(c, power, false); } symbol = Prefixes.concat(prefix, symbol); return new ConventionalUnit<>((AbstractUnit) unit, c, symbol.intern(), (byte) 0, (short) 0); } } } unit = null; } return unit; } /** * If the given system unit should be replaced by pseudo-unit for the purpose of formatting, * returns that pseudo-unit. Otherwise returns {@code null}. This method is for handling the * Special case of {@link Units#KILOGRAM}, to be replaced by {@link Units#GRAM} so a prefix * can be computed. The kilogram may appear in an expression like "kg/m", which we want to * replace by "g/m". We do that by dividing the unit by 1000 (the converter for "milli" prefix). */ @SuppressWarnings("unchecked") static > ConventionalUnit pseudoSystemUnit(final SystemUnit unit) { if ((unit.scope & ~UnitRegistry.SI) == 0 && unit.dimension.numeratorIs('M')) { if (unit == Units.KILOGRAM) { return (ConventionalUnit) Units.GRAM; // Optimization for a common case. } else { String symbol = unit.getSymbol(); if (symbol != null && symbol.length() >= 3 && symbol.startsWith("kg") && !AbstractUnit.isSymbolChar(symbol.codePointAt(2))) { symbol = symbol.substring(1); UnitConverter c = converter('m'); return new ConventionalUnit<>(unit, c, symbol, UnitRegistry.PREFIXABLE, (short) 0).unique(symbol); } } } return null; } }
blob data class t t f data class blob 0 2751 https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-utility/src/main/java/org/apache/sis/measure/Prefixes.java/#L37-L216 1 255 2751
1508 { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } }
blob data class, long method t t f data class, long method blob 0 11154 https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 1 1508 11154
729      { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; }
long method long method, data class t t t  data class   0 6854 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 1 729 6854
1319  {"response": "YES I found bad smells the bad smells are: Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Service public class DepositAccountAssembler { private final PlatformSecurityContext context; private final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; private final SavingsHelper savingsHelper; private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final StaffRepositoryWrapper staffRepository; private final FixedDepositProductRepository fixedDepositProductRepository; private final RecurringDepositProductRepository recurringDepositProductRepository; private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final SavingsAccountChargeAssembler savingsAccountChargeAssembler; private final FromJsonHelper fromApiJsonHelper; private final DepositProductAssembler depositProductAssembler; private final PaymentDetailAssembler paymentDetailAssembler; @Autowired public DepositAccountAssembler(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final ClientRepositoryWrapper clientRepository, final GroupRepositoryWrapper groupRepository, final StaffRepositoryWrapper staffRepository, final FixedDepositProductRepository fixedDepositProductRepository, final SavingsAccountRepositoryWrapper savingsAccountRepository, final SavingsAccountChargeAssembler savingsAccountChargeAssembler, final FromJsonHelper fromApiJsonHelper, final DepositProductAssembler depositProductAssembler, final RecurringDepositProductRepository recurringDepositProductRepository, final AccountTransfersReadPlatformService accountTransfersReadPlatformService, final PlatformSecurityContext context, final PaymentDetailAssembler paymentDetailAssembler) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.clientRepository = clientRepository; this.groupRepository = groupRepository; this.staffRepository = staffRepository; this.fixedDepositProductRepository = fixedDepositProductRepository; this.savingsAccountRepository = savingsAccountRepository; this.savingsAccountChargeAssembler = savingsAccountChargeAssembler; this.fromApiJsonHelper = fromApiJsonHelper; this.depositProductAssembler = depositProductAssembler; this.recurringDepositProductRepository = recurringDepositProductRepository; this.savingsHelper = new SavingsHelper(accountTransfersReadPlatformService); this.context = context; this.paymentDetailAssembler = paymentDetailAssembler; } /** * Assembles a new {@link SavingsAccount} from JSON details passed in * request inheriting details where relevant from chosen * {@link SavingsProduct}. */ public SavingsAccount assembleFrom(final JsonCommand command, final AppUser submittedBy, final DepositAccountType depositAccountType) { final JsonElement element = command.parsedJson(); final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); SavingsProduct product = null; if (depositAccountType.isFixedDeposit()) { product = this.fixedDepositProductRepository.findOne(productId); if (product == null) { throw new FixedDepositProductNotFoundException(productId); } } else if (depositAccountType.isRecurringDeposit()) { product = this.recurringDepositProductRepository.findOne(productId); if (product == null) { throw new RecurringDepositProductNotFoundException(productId); } } if (product == null) { throw new SavingsProductNotFoundException(productId); } Client client = null; Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { final boolean isCalendarInherited = command.booleanPrimitiveValueOfParameterNamed(isCalendarInheritedParamName); client = this.clientRepository.findOneWithNotFoundDetection(clientId, isCalendarInherited); //we need group collection if isCalendarInherited is true accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; } if (group != null && client != null) { if (!group.hasClientAsMember(client)) { throw new ClientNotInGroupException(clientId, groupId); } accountType = AccountType.JLG; if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } } final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); } else { interestRate = product.nominalAnnualInterestRate(); } SavingsCompoundingInterestPeriodType interestCompoundingPeriodType = null; final Integer interestPeriodTypeValue = command.integerValueOfParameterNamed(interestCompoundingPeriodTypeParamName); if (interestPeriodTypeValue != null) { interestCompoundingPeriodType = SavingsCompoundingInterestPeriodType.fromInt(interestPeriodTypeValue); } else { interestCompoundingPeriodType = product.interestCompoundingPeriodType(); } SavingsPostingInterestPeriodType interestPostingPeriodType = null; final Integer interestPostingPeriodTypeValue = command.integerValueOfParameterNamed(interestPostingPeriodTypeParamName); if (interestPostingPeriodTypeValue != null) { interestPostingPeriodType = SavingsPostingInterestPeriodType.fromInt(interestPostingPeriodTypeValue); } else { interestPostingPeriodType = product.interestPostingPeriodType(); } SavingsInterestCalculationType interestCalculationType = null; final Integer interestCalculationTypeValue = command.integerValueOfParameterNamed(interestCalculationTypeParamName); if (interestCalculationTypeValue != null) { interestCalculationType = SavingsInterestCalculationType.fromInt(interestCalculationTypeValue); } else { interestCalculationType = product.interestCalculationType(); } SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = command .integerValueOfParameterNamed(interestCalculationDaysInYearTypeParamName); if (interestCalculationDaysInYearTypeValue != null) { interestCalculationDaysInYearType = SavingsInterestCalculationDaysInYearType.fromInt(interestCalculationDaysInYearTypeValue); } else { interestCalculationDaysInYearType = product.interestCalculationDaysInYearType(); } BigDecimal minRequiredOpeningBalance = null; if (command.parameterExists(minRequiredOpeningBalanceParamName)) { minRequiredOpeningBalance = command.bigDecimalValueOfParameterNamed(minRequiredOpeningBalanceParamName); } else { minRequiredOpeningBalance = product.minRequiredOpeningBalance(); } Integer lockinPeriodFrequency = null; if (command.parameterExists(lockinPeriodFrequencyParamName)) { lockinPeriodFrequency = command.integerValueOfParameterNamed(lockinPeriodFrequencyParamName); } else { lockinPeriodFrequency = product.lockinPeriodFrequency(); } SavingsPeriodFrequencyType lockinPeriodFrequencyType = null; if (command.parameterExists(lockinPeriodFrequencyTypeParamName)) { Integer lockinPeriodFrequencyTypeValue = null; lockinPeriodFrequencyTypeValue = command.integerValueOfParameterNamed(lockinPeriodFrequencyTypeParamName); if (lockinPeriodFrequencyTypeValue != null) { lockinPeriodFrequencyType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue); } } else { lockinPeriodFrequencyType = product.lockinPeriodFrequencyType(); } boolean iswithdrawalFeeApplicableForTransfer = false; if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element, product.currency().getCode()); DepositAccountInterestRateChart accountChart = null; InterestRateChart productChart = null; if (command.parameterExists(chartIdParamName)) { Long chartId = command.longValueOfParameterNamed(chartIdParamName); productChart = product.findChart(chartId); } else { productChart = product.applicableChart(submittedOnDate); } if (productChart != null) { accountChart = DepositAccountInterestRateChart.from(productChart); } boolean withHoldTax = product.withHoldTax(); if (command.parameterExists(withHoldTaxParamName)) { withHoldTax = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); if(withHoldTax && product.getTaxGroup() == null){ throw new UnsupportedParameterException(Arrays.asList(withHoldTaxParamName)); } } SavingsAccount account = null; if (depositAccountType.isFixedDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((FixedDepositProduct) product).depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); FixedDepositAccount fdAccount = FixedDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(fdAccount); fdAccount.validateDomainRules(); account = fdAccount; } else if (depositAccountType.isRecurringDeposit()) { final DepositProductTermAndPreClosure prodTermAndPreClosure = ((RecurringDepositProduct) product) .depositProductTermAndPreClosure(); final DepositAccountTermAndPreClosure accountTermAndPreClosure = this.assembleAccountTermAndPreClosure(command, prodTermAndPreClosure); final DepositProductRecurringDetail prodRecurringDetail = ((RecurringDepositProduct) product).depositRecurringDetail(); final DepositAccountRecurringDetail accountRecurringDetail = this.assembleAccountRecurringDetail(command, prodRecurringDetail.recurringDetail()); RecurringDepositAccount rdAccount = RecurringDepositAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, externalId, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, iswithdrawalFeeApplicableForTransfer, charges, accountTermAndPreClosure, accountRecurringDetail, accountChart, withHoldTax); accountTermAndPreClosure.updateAccountReference(rdAccount); accountRecurringDetail.updateAccountReference(rdAccount); rdAccount.validateDomainRules(); account = rdAccount; } if (account != null) { account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(), depositAccountType.resourceName()); } return account; } public SavingsAccount assembleFrom(final Long savingsId, DepositAccountType depositAccountType) { final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId, depositAccountType); account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } public DepositAccountTermAndPreClosure assembleAccountTermAndPreClosure(final JsonCommand command, final DepositProductTermAndPreClosure productTermAndPreclosure) { final DepositPreClosureDetail productPreClosure = (productTermAndPreclosure == null) ? null : productTermAndPreclosure .depositPreClosureDetail(); final DepositTermDetail productTerm = (productTermAndPreclosure == null) ? null : productTermAndPreclosure.depositTermDetail(); final DepositPreClosureDetail updatedProductPreClosure = this.depositProductAssembler.assemblePreClosureDetail(command, productPreClosure); final DepositTermDetail updatedProductTerm = this.depositProductAssembler.assembleDepositTermDetail(command, productTerm); final BigDecimal depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName); final Integer depositPeriod = command.integerValueOfParameterNamed(depositPeriodParamName); final Integer depositPeriodFrequencyId = command.integerValueOfParameterNamed(depositPeriodFrequencyIdParamName); final SavingsPeriodFrequencyType depositPeriodFrequency = SavingsPeriodFrequencyType.fromInt(depositPeriodFrequencyId); final SavingsAccount account = null; final LocalDate expectedFirstDepositOnDate = command.localDateValueOfParameterNamed(expectedFirstDepositOnDateParamName); final Boolean trasferInterest = command.booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName); // calculate maturity amount final BigDecimal maturityAmount = null;// calculated and updated in // account final LocalDate maturityDate = null;// calculated and updated in account final DepositAccountOnClosureType accountOnClosureType = null; return DepositAccountTermAndPreClosure.createNew(updatedProductPreClosure, updatedProductTerm, account, depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, expectedFirstDepositOnDate, accountOnClosureType, trasferInterest); } public DepositAccountRecurringDetail assembleAccountRecurringDetail(final JsonCommand command, final DepositRecurringDetail prodRecurringDetail) { final BigDecimal recurringDepositAmount = command.bigDecimalValueOfParameterNamed(mandatoryRecommendedDepositAmountParamName); boolean isMandatoryDeposit; boolean allowWithdrawal; boolean adjustAdvanceTowardsFuturePayments; boolean isCalendarInherited; if (command.parameterExists(isMandatoryDepositParamName)) { isMandatoryDeposit = command.booleanObjectValueOfParameterNamed(isMandatoryDepositParamName); } else { isMandatoryDeposit = prodRecurringDetail.isMandatoryDeposit(); } if (command.parameterExists(allowWithdrawalParamName)) { allowWithdrawal = command.booleanObjectValueOfParameterNamed(allowWithdrawalParamName); } else { allowWithdrawal = prodRecurringDetail.allowWithdrawal(); } if (command.parameterExists(adjustAdvanceTowardsFuturePaymentsParamName)) { adjustAdvanceTowardsFuturePayments = command.booleanObjectValueOfParameterNamed(adjustAdvanceTowardsFuturePaymentsParamName); } else { adjustAdvanceTowardsFuturePayments = prodRecurringDetail.adjustAdvanceTowardsFuturePayments(); } if (command.parameterExists(isCalendarInheritedParamName)) { isCalendarInherited = command.booleanObjectValueOfParameterNamed(isCalendarInheritedParamName); } else { isCalendarInherited = false; } final DepositRecurringDetail depositRecurringDetail = DepositRecurringDetail.createFrom(isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments); final DepositAccountRecurringDetail depositAccountRecurringDetail = DepositAccountRecurringDetail.createNew(recurringDepositAmount, depositRecurringDetail, null, isCalendarInherited); return depositAccountRecurringDetail; } public Collection assembleBulkMandatorySavingsAccountTransactionDTOs(final JsonCommand command,final PaymentDetail paymentDetail) { AppUser user = getAppUserIfPresent(); final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final JsonElement element = this.fromApiJsonHelper.parse(json); final Collection savingsAccountTransactions = new ArrayList<>(); final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(element.getAsJsonObject()); final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale); if (element.isJsonObject()) { if (topLevelJsonElement.has(bulkSavingsDueTransactionsParamName) && topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(bulkSavingsDueTransactionsParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsTransactionElement = array.get(i).getAsJsonObject(); final Long savingsId = this.fromApiJsonHelper.extractLongNamed(savingsIdParamName, savingsTransactionElement); final BigDecimal dueAmount = this.fromApiJsonHelper.extractBigDecimalNamed(transactionAmountParamName, savingsTransactionElement, locale); final Integer depositAccountType = this.fromApiJsonHelper.extractIntegerNamed( CollectionSheetConstants.depositAccountTypeParamName, savingsTransactionElement, locale); PaymentDetail detail = paymentDetail; if (paymentDetail == null) { detail = this.paymentDetailAssembler.fetchPaymentDetail(savingsTransactionElement); } final SavingsAccountTransactionDTO savingsAccountTransactionDTO = new SavingsAccountTransactionDTO(formatter, transactionDate, dueAmount, detail, new Date(), savingsId, user, depositAccountType); savingsAccountTransactions.add(savingsAccountTransactionDTO); } } } return savingsAccountTransactions; } private AppUser getAppUserIfPresent() { AppUser user = null; if (this.context != null) { user = this.context.getAuthenticatedUserIfPresent(); } return user; } }
blob data class t t f data class blob 0 10693 https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountAssembler.java/#L107-L472 1 1319 10693
3806  YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery 5. Duplicate code 6. Inconsistent formatting 7. Poor naming conventions 8. Magic numbers 9. Hard-coded values 10. Excessive commenting I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); }
long method  Long method2 Feature envy3 Data class4 Shotgun surgery5 Duplicate code6 Inconsistent formatting7 Poor naming conventions8 Magic numbers9 Hard-coded values t f t     0 9657 https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 2 3806 9657
837   YES I found bad smells the bad smells are: 1.Feature envy 2.Data class 3.Long method I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type XPathFilter2ParameterSpec"); } this.params = params; } public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { throw new InvalidAlgorithmParameterException(me); } } private void unmarshalParams(Element curXPathElem) throws MarshalException { List list = new ArrayList<>(); Element currentElement = curXPathElem; while (currentElement != null) { String xPath = currentElement.getFirstChild().getNodeValue(); String filterVal = DOMUtils.getAttributeValue(currentElement, "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if ("intersect".equals(filterVal)) { filter = XPathType.Filter.INTERSECT; } else if ("subtract".equals(filterVal)) { filter = XPathType.Filter.SUBTRACT; } else if ("union".equals(filterVal)) { filter = XPathType.Filter.UNION; } else { throw new MarshalException("Unknown XPathType filter type" + filterVal); } NamedNodeMap attributes = currentElement.getAttributes(); if (attributes != null) { int length = attributes.getLength(); Map namespaceMap = new HashMap<>(length); for (int i = 0; i < length; i++) { Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && "xmlns".equals(prefix)) { namespaceMap.put(attr.getLocalName(), attr.getValue()); } } list.add(new XPathType(xPath, filter, namespaceMap)); } else { list.add(new XPathType(xPath, filter)); } currentElement = DOMUtils.getNextSiblingElement(currentElement); } this.params = new XPathFilter2ParameterSpec(list); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = prefix == null || prefix.length() == 0 ? "xmlns" : "xmlns:" + prefix; @SuppressWarnings("unchecked") List xpathList = xp.getXPathList(); for (XPathType xpathType : xpathList) { Element elem = DOMUtils.createElement(ownerDoc, "XPath", Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); DOMUtils.setAttribute(elem, "Filter", xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, Transform.XPATH2); // add namespace attributes, if necessary @SuppressWarnings("unchecked") Set> entries = xpathType.getNamespaceMap().entrySet(); for (Map.Entry entry : entries) { elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + entry.getKey(), entry.getValue()); } transformElem.appendChild(elem); } } }
blob Feature envy2Data class3Long method t f f .Feature envy2.Data class3.Long method blob 0 7771 https://github.com/apache/santuario-java/blob/fa12dc57a16fbcd637c2aac6f3af3db19fe4b187/src/main/java/org/apache/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java/#L58-L161 2 837 7771
2115      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } }
long method long method, data class t t t  data class   0 13193 https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 1 2115 13193
2211 {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class Parser { public static GetOrderReferenceDetailsResponseData getOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final GetOrderReferenceDetailsResponse response = marshalXML(GetOrderReferenceDetailsResponse.class, rawResponse); return new GetOrderReferenceDetailsResponseData(response, rawResponse); } public static SetOrderReferenceDetailsResponseData setOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final SetOrderReferenceDetailsResponse response = marshalXML(SetOrderReferenceDetailsResponse.class, rawResponse); return new SetOrderReferenceDetailsResponseData(response, rawResponse); } public static AuthorizeResponseData getAuthorizeData(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeResponse response = marshalXML(AuthorizeResponse.class, rawResponse); return new AuthorizeResponseData(response, rawResponse); } public static GetAuthorizationDetailsResponseData getAuthorizationDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetAuthorizationDetailsResponse response = marshalXML(GetAuthorizationDetailsResponse.class, rawResponse); return new GetAuthorizationDetailsResponseData(response, rawResponse); } public static CaptureResponseData getCapture(ResponseData rawResponse) throws AmazonServiceException { final CaptureResponse response = marshalXML(CaptureResponse.class, rawResponse); return new CaptureResponseData(response, rawResponse); } public static GetCaptureDetailsResponseData getCaptureDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetCaptureDetailsResponse response = marshalXML(GetCaptureDetailsResponse.class, rawResponse); return new GetCaptureDetailsResponseData(response, rawResponse); } public static ConfirmOrderReferenceResponseData confirmOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ConfirmOrderReferenceResponse response = marshalXML(ConfirmOrderReferenceResponse.class, rawResponse); return new ConfirmOrderReferenceResponseData(response, rawResponse); } public static CloseAuthorizationResponseData closeAuthorizationResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseAuthorizationResponse response = marshalXML(CloseAuthorizationResponse.class, rawResponse); return new CloseAuthorizationResponseData(response, rawResponse); } public static CancelOrderReferenceResponseData getCancelOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CancelOrderReferenceResponse response = marshalXML(CancelOrderReferenceResponse.class, rawResponse); return new CancelOrderReferenceResponseData(response, rawResponse); } public static CloseOrderReferenceResponseData getCloseOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CloseOrderReferenceResponse response = marshalXML(CloseOrderReferenceResponse.class, rawResponse); return new CloseOrderReferenceResponseData(response, rawResponse); } public static RefundResponseData getRefundData(ResponseData rawResponse) throws AmazonServiceException { final RefundResponse response = marshalXML(RefundResponse.class, rawResponse); return new RefundResponseData(response, rawResponse); } public static GetRefundDetailsResponseData getRefundDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetRefundDetailsResponse response = marshalXML(GetRefundDetailsResponse.class, rawResponse); return new GetRefundDetailsResponseData(response, rawResponse); } public static GetBillingAgreementDetailsResponseData getBillingAgreementDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetBillingAgreementDetailsResponse response = marshalXML(GetBillingAgreementDetailsResponse.class, rawResponse); return new GetBillingAgreementDetailsResponseData(response, rawResponse); } public static SetBillingAgreementDetailsResponseData getSetBillingAgreementDetailsResponse(ResponseData rawResponse) throws AmazonServiceException { final SetBillingAgreementDetailsResponse response = marshalXML(SetBillingAgreementDetailsResponse.class, rawResponse); return new SetBillingAgreementDetailsResponseData(response, rawResponse); } public static ValidateBillingAgreementResponseData getValidateBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ValidateBillingAgreementResponse response = marshalXML(ValidateBillingAgreementResponse.class, rawResponse); return new ValidateBillingAgreementResponseData(response, rawResponse); } public static ConfirmBillingAgreementResponseData confirmBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ConfirmBillingAgreementResponse response = marshalXML(ConfirmBillingAgreementResponse.class, rawResponse); return new ConfirmBillingAgreementResponseData(response, rawResponse); } public static AuthorizeOnBillingAgreementResponseData getAuthorizeOnBillingAgreement(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeOnBillingAgreementResponse response = marshalXML(AuthorizeOnBillingAgreementResponse.class, rawResponse); return new AuthorizeOnBillingAgreementResponseData(response, rawResponse); } public static CloseBillingAgreementResponseData closeBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseBillingAgreementResponse response = marshalXML(CloseBillingAgreementResponse.class, rawResponse); return new CloseBillingAgreementResponseData(response, rawResponse); } public static GetProviderCreditDetailsResponseData getGetProviderCreditDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditDetailsResponse response = marshalXML(GetProviderCreditDetailsResponse.class, rawResponse); return new GetProviderCreditDetailsResponseData(response, rawResponse); } public static GetProviderCreditReversalDetailsResponseData getProviderCreditReversalDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditReversalDetailsResponse response = marshalXML(GetProviderCreditReversalDetailsResponse.class, rawResponse); return new GetProviderCreditReversalDetailsResponseData(response, rawResponse); } public static ReverseProviderCreditResponseData getReverseProviderCreditResponseData(ResponseData rawResponse) throws AmazonServiceException { final ReverseProviderCreditResponse response = marshalXML(ReverseProviderCreditResponse.class, rawResponse); return new ReverseProviderCreditResponseData(response, rawResponse); } public static GetServiceStatusResponseData getServiceStatus( ResponseData rawResponse) throws AmazonServiceException { final GetServiceStatusResponse response = marshalXML( GetServiceStatusResponse.class, rawResponse); return new GetServiceStatusResponseData(response, rawResponse); } public static CreateOrderReferenceForIdResponseData createOrderReferenceForId( ResponseData rawResponse) throws AmazonServiceException { final CreateOrderReferenceForIdResponse response = marshalXML( CreateOrderReferenceForIdResponse.class, rawResponse); return new CreateOrderReferenceForIdResponseData(response, rawResponse); } public static ListOrderReferenceResponseData listOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceResponse response = marshalXML(ListOrderReferenceResponse.class, rawResponse); return new ListOrderReferenceResponseData(response, rawResponse); } public static ListOrderReferenceByNextTokenResponseData listOrderReferenceByNextToken(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceByNextTokenResponse response = marshalXML(ListOrderReferenceByNextTokenResponse.class, rawResponse); return new ListOrderReferenceByNextTokenResponseData(response, rawResponse); } public static SetOrderAttributesResponseData setOrderAttributes(ResponseData rawResponse) throws AmazonServiceException { final SetOrderAttributesResponse response = marshalXML(SetOrderAttributesResponse.class, rawResponse); return new SetOrderAttributesResponseData(response, rawResponse); } public static GetMerchantAccountStatusResponseData getMerchantAccountStatus(ResponseData rawResponse) throws AmazonServiceException { final GetMerchantAccountStatusResponse response = marshalXML(GetMerchantAccountStatusResponse.class, rawResponse); return new GetMerchantAccountStatusResponseData(response, rawResponse); } public static T marshalXML(Class clazz, ResponseData rawResponse) throws AmazonServiceException { try { if (rawResponse.getStatusCode() == 200) { T responseObject = null; final JAXBContext context = JAXBContext.newInstance(clazz); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); responseObject = (T) unmarshaller.unmarshal(xmlStreamReader); return responseObject; } else { generateErrorException(rawResponse); } } catch (JAXBException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } return null; } public static void generateErrorException(ResponseData rawResponse) throws AmazonServiceException, JAXBException { final JAXBContext context = JAXBContext.newInstance(ErrorResponse.class); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); try { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); final ErrorResponse result = (ErrorResponse) unmarshaller.unmarshal(xmlStreamReader); throw new AmazonServiceException(result, rawResponse); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } } }
blob blob, data class t t t  data class   0 13521 https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/parser/Parser.java/#L57-L252 1 2211 13521
60  { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public static class Builder { final SystemModuleFinder systemModulePath; final Set rootModules = new HashSet<>(); final List initialArchives = new ArrayList<>(); final List paths = new ArrayList<>(); final List classPaths = new ArrayList<>(); ModuleFinder upgradeModulePath; ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; boolean addAllSystemModules; boolean allModules; Runtime.Version version; public Builder() { this.systemModulePath = new SystemModuleFinder(); } public Builder(String javaHome) throws IOException { this.systemModulePath = SystemModuleFinder.JAVA_HOME.equals(javaHome) ? new SystemModuleFinder() : new SystemModuleFinder(javaHome); } public Builder upgradeModulePath(String upgradeModulePath) { this.upgradeModulePath = createModulePathFinder(upgradeModulePath); return this; } public Builder appModulePath(String modulePath) { this.appModulePath = createModulePathFinder(modulePath); return this; } public Builder addmods(Set addmods) { for (String mn : addmods) { switch (mn) { case ALL_MODULE_PATH: this.addAllApplicationModules = true; break; case ALL_DEFAULT: this.addAllDefaultModules = true; break; case ALL_SYSTEM: this.addAllSystemModules = true; break; default: this.rootModules.add(mn); } } return this; } /* * This method is for --check option to find all target modules specified * in qualified exports. * * Include all system modules and modules found on modulepath */ public Builder allModules() { this.allModules = true; return this; } public Builder multiRelease(Runtime.Version version) { this.version = version; return this; } public Builder addRoot(Path path) { Archive archive = Archive.getInstance(path, version); if (archive.contains(MODULE_INFO)) { paths.add(path); } else { initialArchives.add(archive); } return this; } public Builder addClassPath(String classPath) { this.classPaths.addAll(getClassPaths(classPath)); return this; } public JdepsConfiguration build() throws IOException { ModuleFinder finder = systemModulePath; if (upgradeModulePath != null) { finder = ModuleFinder.compose(upgradeModulePath, systemModulePath); } if (appModulePath != null) { finder = ModuleFinder.compose(finder, appModulePath); } if (!paths.isEmpty()) { ModuleFinder otherModulePath = ModuleFinder.of(paths.toArray(new Path[0])); finder = ModuleFinder.compose(finder, otherModulePath); // add modules specified on command-line (convenience) as root set otherModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } if ((addAllApplicationModules || allModules) && appModulePath != null) { appModulePath.findAll().stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } // no archive is specified for analysis // add all system modules as root if --add-modules ALL-SYSTEM is specified if (addAllSystemModules && rootModules.isEmpty() && initialArchives.isEmpty() && classPaths.isEmpty()) { systemModulePath.findAll() .stream() .map(mref -> mref.descriptor().name()) .forEach(rootModules::add); } return new JdepsConfiguration(systemModulePath, finder, rootModules, classPaths, initialArchives, addAllDefaultModules, allModules, version); } private static ModuleFinder createModulePathFinder(String mpaths) { if (mpaths == null) { return null; } else { String[] dirs = mpaths.split(File.pathSeparator); Path[] paths = new Path[dirs.length]; int i = 0; for (String dir : dirs) { paths[i++] = Paths.get(dir); } return ModuleFinder.of(paths); } } /* * Returns the list of Archive specified in cpaths and not included * initialArchives */ private List getClassPaths(String cpaths) { if (cpaths.isEmpty()) { return Collections.emptyList(); } List paths = new ArrayList<>(); for (String p : cpaths.split(File.pathSeparator)) { if (p.length() > 0) { // wildcard to parse all JAR files e.g. -classpath dir/* int i = p.lastIndexOf(".*"); if (i > 0) { Path dir = Paths.get(p.substring(0, i)); try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.jar")) { for (Path entry : stream) { paths.add(entry); } } catch (IOException e) { throw new UncheckedIOException(e); } } else { paths.add(Paths.get(p)); } } } return paths; } }
blob data class, long method t t f data class, long method blob 0 1007 https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java/#L476-L649 1 60 1007
1416 {"response": "YES I found bad smells\nthe bad smells are: 1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
blob 1. data class t t f 1. data class blob 0 10912 https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 1 1416 10912
2400 {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } }
long method long method, data class t t t  data class   0 14379 https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 1 2400 14379
1631   YES I found bad smells The bad smells are: 1. Long Method, 2. Feature Envy, 3. Inappropriate Intimacy, 4. Primitive Obsession, 5. Inconsistent Naming, 6. Data Class, 7. Long Parameter List I need to check if the Java code below contains code smells (aka bad smells). Could you please
identify which smells occur in the following code? However, do not describe the smells, just list them. Please start
your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO,
I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your
answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } }
blob  Long Method, 2 Feature Envy, 3 Inappropriate Intimacy, 4 Primitive Obsession, 5 Inconsistent Naming, 6 Data Class, 7 Long Parameter List t f f . Long Method, 2. Feature Envy, 3. Inappropriate Intimacy, 4. Primitive Obsession, 5. Inconsistent Naming, 6. Data Class, 7. Long Parameter List blob 0 11508 https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 2 1631 11508
1166 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } }
blob long method, data class t t f long method, data class blob 0 10184 https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 1 1166 10184
1462 {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } }
blob blob, data class, long method t t t  data class, long method   0 11026 https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 1 1462 11026
1643 { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); }
blob Long Method, Data Class t f f Long Method, Data Class blob 0 11556 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 1 1643 11556
2417 {"response":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ElasticsearchClientFactory { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String ES_SETTINGS_KEY = "es.client.settings"; // es config key in global config /** * Creates an Elasticsearch client from settings provided via the global config. * * @return new client */ public static ElasticsearchClient create(Map globalConfig) { ElasticsearchClientConfig esClientConfig = new ElasticsearchClientConfig( getEsSettings(globalConfig)); HttpHost[] httpHosts = getHttpHosts(globalConfig, esClientConfig.getConnectionScheme()); RestClientBuilder builder = RestClient.builder(httpHosts); builder.setRequestConfigCallback(reqConfigBuilder -> { // Modifies request config builder with connection and socket timeouts. // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_timeouts.html reqConfigBuilder.setConnectTimeout(esClientConfig.getConnectTimeoutMillis()); reqConfigBuilder.setSocketTimeout(esClientConfig.getSocketTimeoutMillis()); return reqConfigBuilder; }); builder.setMaxRetryTimeoutMillis(esClientConfig.getMaxRetryTimeoutMillis()); builder.setHttpClientConfigCallback(clientBuilder -> { clientBuilder.setDefaultIOReactorConfig(getIOReactorConfig(esClientConfig)); clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider(esClientConfig)); clientBuilder.setSSLContext(getSSLContext(esClientConfig)); return clientBuilder; }); RestClient lowLevelClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelClient); return new ElasticsearchClient(lowLevelClient, client); } private static Map getEsSettings(Map globalConfig) { return (Map) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); } private static HttpHost[] getHttpHosts(Map globalConfiguration, String scheme) { List hps = ElasticsearchUtils.getIps(globalConfiguration); HttpHost[] httpHosts = new HttpHost[hps.size()]; int i = 0; for (HostnamePort hp : hps) { httpHosts[i++] = new HttpHost(hp.hostname, hp.port, scheme); } return httpHosts; } /** * Creates config with setting for num connection threads. Default is ES client default, * which is 1 to num processors per the documentation. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_number_of_threads.html */ private static IOReactorConfig getIOReactorConfig(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.getNumClientConnectionThreads().isPresent()) { Integer numThreads = esClientConfig.getNumClientConnectionThreads().get(); LOG.info("Setting number of client connection threads: {}", numThreads); return IOReactorConfig.custom().setIoThreadCount(numThreads).build(); } else { return IOReactorConfig.DEFAULT; } } private static CredentialsProvider getCredentialsProvider( ElasticsearchClientConfig esClientConfig) { Optional> credentials = esClientConfig.getCredentials(); if (credentials.isPresent()) { LOG.info( "Found auth credentials - setting up user/pass authenticated client connection for ES."); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials( credentials.get().getKey(), credentials.get().getValue()); credentialsProvider.setCredentials(AuthScope.ANY, upcredentials); return credentialsProvider; } else { LOG.info( "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection."); return null; } } /** * Setup connection encryption details (SSL) if applicable. * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can * also optionally set keystore.password and keystore.type. * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html * * Other guidance on the HTTP Component library and configuring SSL connections. * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask. * * JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html * * Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html */ private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) { if (esClientConfig.isSSLEnabled()) { LOG.info("Configuring client for SSL connection."); if (!esClientConfig.getKeyStorePath().isPresent()) { throw new IllegalStateException("KeyStore path must be provided for SSL connection."); } Optional optKeyStorePass = esClientConfig.getKeyStorePassword(); char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null); KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(), keyStorePass); try { SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); return sslBuilder.build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalStateException("Unable to load truststore.", e); } } return null; } private static KeyStore getStore(String type, Path path, char[] pass) { KeyStore store; try { store = KeyStore.getInstance(type); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get keystore type '" + type + "'", e); } try (InputStream is = Files.newInputStream(path)) { store.load(is, pass); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { throw new IllegalStateException("Unable to load keystore from path '" + path + "'", e); } return store; } }
blob long method, data class t t f long method, data class blob 0 14422 https://github.com/apache/metron/blob/17b31b48f59627a9e768a5cbe0be7ac55b5b04f8/metron-platform/metron-elasticsearch/src/main/java/org/apache/metron/elasticsearch/client/ElasticsearchClientFactory.java/#L57-L189 1 2417 14422
485      { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class ClassStructureImplByJDK extends FamilyClassStructure { private final Class clazz; private String javaClassName; public ClassStructureImplByJDK(final Class clazz) { this.clazz = clazz; } private ClassStructure newInstance(final Class clazz) { if (null == clazz) { return null; } return new ClassStructureImplByJDK(clazz); } private List newInstances(final Class[] classArray) { final List classStructures = new ArrayList(); if (null != classArray) { for (final Class clazz : classArray) { final ClassStructure classStructure = newInstance(clazz); if (null != classStructure) { classStructures.add(classStructure); } } } return classStructures; } @Override public String getJavaClassName() { return null != javaClassName ? javaClassName : (javaClassName = getJavaClassName(clazz)); } private String getJavaClassName(Class clazz) { if (clazz.isArray()) { return getJavaClassName(clazz.getComponentType()) + "[]"; } return clazz.getName(); } @Override public ClassLoader getClassLoader() { return clazz.getClassLoader(); } @Override public ClassStructure getSuperClassStructure() { // 过滤掉Object.class return Object.class.equals(clazz.getSuperclass()) ? null : newInstance(clazz.getSuperclass()); } @Override public List getInterfaceClassStructures() { return newInstances(clazz.getInterfaces()); } private Class[] getAnnotationTypeArray(final Annotation[] annotationArray) { final Collection annotationTypes = new ArrayList(); for (final Annotation annotation : annotationArray) { if (annotation.getClass().isAnnotation()) { annotationTypes.add(annotation.getClass()); } for (final Class annotationInterfaceClass : annotation.getClass().getInterfaces()) { if (annotationInterfaceClass.isAnnotation()) { annotationTypes.add(annotationInterfaceClass); } } } return annotationTypes.toArray(new Class[0]); } private final LazyGet> annotationTypeClassStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { return Collections.unmodifiableList(newInstances(getAnnotationTypeArray(clazz.getDeclaredAnnotations()))); } }; @Override public List getAnnotationTypeClassStructures() { return annotationTypeClassStructuresLazyGet.get(); } private BehaviorStructure newBehaviorStructure(final Method method) { return new BehaviorStructure( new AccessImplByJDKBehavior(method), method.getName(), this, newInstance(method.getReturnType()), newInstances(method.getParameterTypes()), newInstances(method.getExceptionTypes()), newInstances(getAnnotationTypeArray(method.getDeclaredAnnotations())) ); } private BehaviorStructure newBehaviorStructure(final Constructor constructor) { return new BehaviorStructure( new AccessImplByJDKBehavior(constructor), "", this, this, newInstances(constructor.getParameterTypes()), newInstances(constructor.getExceptionTypes()), newInstances(getAnnotationTypeArray(constructor.getDeclaredAnnotations())) ); } private final LazyGet> behaviorStructuresLazyGet = new LazyGet>() { @Override protected List initialValue() { final List behaviorStructures = new ArrayList(); for (final Constructor constructor : clazz.getDeclaredConstructors()) { behaviorStructures.add(newBehaviorStructure(constructor)); } for (final Method method : clazz.getDeclaredMethods()) { behaviorStructures.add(newBehaviorStructure(method)); } return Collections.unmodifiableList(behaviorStructures); } }; @Override public List getBehaviorStructures() { return behaviorStructuresLazyGet.get(); } @Override public Access getAccess() { return new AccessImplByJDKClass(clazz); } @Override public String toString() { return "ClassStructureImplByJDK{" + "javaClassName='" + javaClassName + '\'' + '}'; } }
blob long method, data class t t f long method, data class blob 0 4746 https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/util/matcher/structure/ClassStructureImplByJDK.java/#L109-L252 1 485 4746
2125 {"answer":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } }
blob long method, data class t t f long method, data class blob 0 13220 https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 1 2125 13220
4370 {"response":"YES I found bad smells","bad smells":["1. Long method","2. Long parameter list","3. Data class"]} I need to check if the Java code below contains code smells (aka bad smells).
Could you please identify which smells occur in the following code? However, do not describe the smells,
just list them.
Please start your answer with "YES I found bad smells" when you find any bad smell.
Otherwise, start your answer with "NO, I did not find any bad smell".
When you start to list the detected bad smells, always put in your answer "the bad smells
are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy:
public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } }
blob 1. long method, 2. long parameter list, 3. data class t t f 1. long method, 2. long parameter list, 3. data class blob 0 11535 https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 2 4370 11535
509 {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class AnnotationViewerMain extends JFrame { private static final long serialVersionUID = -3201723535833938833L; private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n" + "1) In the \"Input Directory\" field, either type or use the browse\n" + "button to select a directory containing the analyzed documents\n " + "(in XMI or XCAS format) that you want to view.\n\n" + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n" + "button to select the TypeSystem or AE descriptor for the AE that generated the\n" + "XMI or XCAS files. (This is needed for type system infornation only.\n" + "Analysis will not be redone.)\n\n" + "3) Click the \"View\" button at the buttom of the window.\n\n" + "A list of the analyzed documents will be displayed.\n\n\n" + "4) Select the view type -- either the Java annotation viewer, HTML,\n" + "or XML. The Java annotation viewer is recommended.\n\n" + "5) Double-click on a document to view it.\n"; private File uimaHomeDir; private FileSelector inputFileSelector; private FileSelector taeDescriptorFileSelector; private JButton viewButton; private JDialog aboutDialog; /** Stores user preferences */ private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer"); /** * Constructor. Sets up the GUI. */ public AnnotationViewerMain() { super("Annotation Viewer"); // set UIMA home dir uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima")); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // I don't think this should ever happen, but if it does just print error and continue // with defalt look and feel System.err.println("Could not set look and feel: " + e.getMessage()); } // UIManager.put("Panel.background",Color.WHITE); // Need to set other colors as well // Set frame icon image try { this.setIconImage(Images.getImage(Images.MICROSCOPE)); // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage()); } catch (IOException e) { System.err.println("Image could not be loaded: " + e.getMessage()); } this.getContentPane().setBackground(Color.WHITE); // create about dialog aboutDialog = new AboutDialog(this, "About Annotation Viewer"); // Create Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Menu Items JMenuItem aboutMenuItem = new JMenuItem("About"); JMenuItem helpMenuItem = new JMenuItem("Help"); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); helpMenu.add(helpMenuItem); menuBar.add(fileMenu); menuBar.add(helpMenu); // Labels to identify the text fields final Caption labelInputDir = new Caption("Input Directory: "); final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: "); JPanel controlPanel = new JPanel(); controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); controlPanel.setLayout(new SpringLayout()); // Once we add components to controlPanel, we'll // call SpringUtilities::makeCompactGrid on it. // controlPanel.setLayout(new GridLayout(4, 2, 8, 4)); // Set default values for input fields File inputDir = new File(uimaHomeDir, "examples/data/processed"); inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY, inputDir); inputFileSelector.setSelected(inputDir.getAbsolutePath()); taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY, uimaHomeDir); File descriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath()); controlPanel.add(labelInputDir); controlPanel.add(inputFileSelector); controlPanel.add(labelStyleMapFile); controlPanel.add(taeDescriptorFileSelector); SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols 4, 4, // initX, initY 4, 4); // xPad, yPad // Event Handlling of "Exit" Menu Item exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { savePreferences(); System.exit(0); } }); // Event Handlling of "About" Menu Item aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { aboutDialog.setVisible(true); } }); // Event Handlling of "Help" Menu Item helpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE, "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE); } }); // Add the panels to the frame Container contentPanel = getContentPane(); contentPanel.add(controlPanel, BorderLayout.CENTER); // add banner JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER)); contentPanel.add(banner, BorderLayout.NORTH); // Add the view Button to run TAE viewButton = new JButton("View"); // Add the view button to another panel JPanel lowerButtonsPanel = new JPanel(); lowerButtonsPanel.add(viewButton); contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH); setContentPane(contentPanel); // Event Handling of view Button viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { try { viewDocuments(); } catch (Exception e) { displayError(e); } } }); // load user preferences if (System.getProperty("uima.noprefs") == null) { restorePreferences(); } } public void viewDocuments() throws InvalidXMLException, IOException, ResourceInitializationException { File descriptorFile = new File(taeDescriptorFileSelector.getSelected()); if (!descriptorFile.exists() || descriptorFile.isDirectory()) { displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist."); return; } File inputDir = new File(inputFileSelector.getSelected()); if (!inputDir.exists() || !inputDir.isDirectory()) { displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist."); return; } // parse descriptor. Could be either AE or TypeSystem descriptor Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile)); // instantiate CAS to get type system. Also build style map file if there is none. CAS cas; File styleMapFile; if (descriptor instanceof AnalysisEngineDescription) { cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor); styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor, descriptorFile .getPath()); } else if (descriptor instanceof TypeSystemDescription) { TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor; tsDesc.resolveImports(); cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]); styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath()); } else { displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\"" + "Must be either an AnalysisEngine or TypeSystem descriptor."); return; } // create Annotation Viewer Main Panel PrefsMediator prefsMed = new PrefsMediator(); // set OUTPUT dir in PrefsMediator, not input dir. // PrefsMediator is also used in DocumentAnalyzer, where the // output dir is the directory containing XCAS files. prefsMed.setOutputDir(inputDir.toString()); AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents", prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas); viewerDialog.pack(); viewerDialog.setModal(true); viewerDialog.setVisible(true); } /** * @param tad * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData()); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * @param tsd * @param descFileName * @return the style map file * @throws IOException - */ private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException { File styleMapFile = getStyleMapFileName(descFileName); if (!styleMapFile.exists()) { // generate default style map String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd); PrintWriter writer; writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile))); writer.println(xml); writer.close(); } return styleMapFile; } /** * Gets the name of the style map file for the given AE or TypeSystem descriptor filename. */ public File getStyleMapFileName(String aDescriptorFileName) { String baseName; int index = aDescriptorFileName.lastIndexOf("."); if (index > 0) { baseName = aDescriptorFileName.substring(0, index); } else { baseName = aDescriptorFileName; } return new File(baseName + "StyleMap.xml"); } public static void main(String[] args) { final AnnotationViewerMain frame = new AnnotationViewerMain(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.savePreferences(); System.exit(0); } }); frame.pack(); frame.setVisible(true); } /** * Save user's preferences using Java's Preference API. */ public void savePreferences() { prefs.put("inDir", inputFileSelector.getSelected()); prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected()); } /** * Reset GUI to preferences last saved via {@link #savePreferences}. */ public void restorePreferences() { // figure defaults File defaultInputDir = new File(uimaHomeDir, "examples/data/processed"); File defaultTaeDescriptorFile = new File(uimaHomeDir, "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml"); // restore preferences inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString())); taeDescriptorFileSelector.setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile .toString())); } /** * Displays an error message to the user. * * @param aErrorString * error message to display */ public void displayError(String aErrorString) { // word-wrap long mesages StringBuffer buf = new StringBuffer(aErrorString.length()); final int CHARS_PER_LINE = 80; int charCount = 0; StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true); while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); if (tok.equals("\n")) { buf.append("\n"); charCount = 0; } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) { buf.append("\n").append(tok); charCount = tok.length(); } else { buf.append(tok); charCount += tok.length(); } } JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error", JOptionPane.ERROR_MESSAGE); } /** * Displays an error message to the user. * * @param aThrowable * Throwable whose message is to be displayed. */ public void displayError(Throwable aThrowable) { aThrowable.printStackTrace(); String message = aThrowable.toString(); // For UIMAExceptions or UIMARuntimeExceptions, add cause info. // We have to go through this nonsense to support Java 1.3. // In 1.4 all exceptions can have a cause, so this wouldn't involve // all of this typecasting. while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) { if (aThrowable instanceof UIMAException) { aThrowable = ((UIMAException) aThrowable).getCause(); } else if (aThrowable instanceof UIMARuntimeException) { aThrowable = ((UIMARuntimeException) aThrowable).getCause(); } if (aThrowable != null) { message += ("\nCausedBy: " + aThrowable.toString()); } } displayError(message); } /* * (non-Javadoc) * * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { return new Dimension(640, 200); } }
blob data class, long method t t f data class, long method blob 0 5182 https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-tools/src/main/java/org/apache/uima/tools/AnnotationViewerMain.java/#L78-L459 1 509 5182
1748 {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); }
blob Blob, Data Class, Long Method t f t  Data Class, Long Method   0 11856 https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 1 1748 11856
879  { "output": "YES, I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } }
feature envy long method, data class t t f long method, data class feature envy 0 8015 https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 1 879 8015
1949 {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); }
blob blob, data class, long method t t t  data class, long method   0 12529 https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 1 1949 12529
946      { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
} return modulesForAggregatedProject( project, reactorProjectsMap ); } /** * Recursively add the modules of the aggregatedProject to the set of aggregatedModules. * * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects
feature envy data class, long method t t f data class, long method feature envy 0 8494 https://github.com/apache/maven-javadoc-plugin/blob/3ab15eb9ec04c82a4b99dc47d0879e77f989d74f/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java/#L2358-L2367 1 946 8494
2619  { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } }
blob long method, data class t t f long method, data class blob 0 15051 https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 1 2619 15051
2370 { "output": "YES I found bad smells, the bad smells are: 1. Long Method, 2. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
class ManualImplementationLoaderService { private static final String SERVICE_CONFIG = "META-INF/services/"; private static final String FILE_ENCODING = "UTF-8"; protected List> foundServiceClasses = new ArrayList<>(); private Class serviceType; private ClassLoader currentClassLoader; ManualImplementationLoaderService(Class serviceType, ClassLoader currentClassLoader) { this.serviceType = serviceType; this.currentClassLoader = currentClassLoader; } List loadServiceImplementations() { List> result = resolveServiceImplementations(); if (result == null) { return Collections.emptyList(); } List foundServices = new ArrayList<>(); for (Class serviceClass : result) { foundServices.add(createInstance(serviceClass)); } return foundServices; } private List> resolveServiceImplementations() { for (URL configFile : getConfigFileList()) { loadConfiguredServices(configFile); } return foundServiceClasses; } private List getConfigFileList() { List serviceFiles = new ArrayList<>(); try { Enumeration serviceFileEnumerator = currentClassLoader.getResources(getConfigFileLocation()); while (serviceFileEnumerator.hasMoreElements()) { serviceFiles.add(serviceFileEnumerator.nextElement()); } } catch (Exception e) { throw new IllegalStateException( "Failed to load " + serviceType.getName() + " configured in " + getConfigFileLocation(), e); } return serviceFiles; } private String getConfigFileLocation() { return SERVICE_CONFIG + serviceType.getName(); } private void loadConfiguredServices(URL serviceFile) { InputStream inputStream = null; try { String serviceClassName; inputStream = serviceFile.openStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, FILE_ENCODING)); while ((serviceClassName = bufferedReader.readLine()) != null) { serviceClassName = extractConfiguredServiceClassName(serviceClassName); if (!"".equals(serviceClassName)) { loadService(serviceClassName); } } } catch (Exception e) { throw new IllegalStateException("Failed to process service-config: " + serviceFile, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { throw new IllegalStateException("Failed to close " + serviceFile, e); } } } } private String extractConfiguredServiceClassName(String currentConfigLine) { int startOfComment = currentConfigLine.indexOf('#'); if (startOfComment > -1) { currentConfigLine = currentConfigLine.substring(0, startOfComment); } return currentConfigLine.trim(); } private void loadService(String serviceClassName) { Class serviceClass = (Class) loadClass(serviceClassName); if (serviceClass != null && !foundServiceClasses.contains(serviceClass)) { foundServiceClasses.add(serviceClass); } else if (serviceClass == null) { throw new IllegalStateException(serviceClassName + " couldn't be loaded. " + "Please ensure that this class is in the classpath or remove the entry from " + getConfigFileLocation() + "."); } } private Class loadClass(String serviceClassName) { Class targetClass = ClassUtil.getClassFromName(serviceClassName); if (targetClass == null) { targetClass = loadClassForName(serviceClassName, currentClassLoader); if (targetClass == null) { return null; } } return targetClass.asSubclass(serviceType); } private static Class loadClassForName(String serviceClassName, ClassLoader classLoader) { if (classLoader == null) { return null; } try { return classLoader.loadClass(serviceClassName); } catch (Exception e) { return loadClassForName(serviceClassName, classLoader.getParent()); } } private T createInstance(Class serviceClass) { try { Constructor constructor = serviceClass.getDeclaredConstructor(); constructor.setAccessible(true); return (T) constructor.newInstance(); } catch (Exception e) { return null; } } /** * {@inheritDoc} */ @Override public String toString() { return "Config file: " + getConfigFileLocation(); } }
blob 1. long method, 2. data class t t f 1. long method, 2. data class blob 0 14305 https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/webbeans-impl/src/main/java/org/apache/webbeans/service/ManualImplementationLoaderService.java/#L36-L228 1 2370 14305
1772  { "output": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } }
blob long method, data class t t f long method, data class blob 0 11921 https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 1 1772 11921
1375 {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class AttributeUtils { public static Attribute[] readAttributes(DataInputStream dataInputstream, ConstantPool cpool) { try { int length = dataInputstream.readUnsignedShort(); if (length == 0) { return Attribute.NoAttributes; } Attribute[] attrs = new Attribute[length]; for (int i = 0; i < length; i++) { attrs[i] = Attribute.readAttribute(dataInputstream, cpool); } return attrs; } catch (IOException e) { throw new ClassFormatException("IOException whilst reading set of attributes: " + e.toString()); } } /** Write (serialize) a set of attributes into a specified output stream */ public static void writeAttributes(Attribute[] attributes, DataOutputStream file) throws IOException { if (attributes == null) { file.writeShort(0); } else { file.writeShort(attributes.length); for (int i = 0; i < attributes.length; i++) { attributes[i].dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SIGNATURE) { return (Signature) attributes[i]; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_CODE) { return (Code) attributes[i]; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { return (ExceptionTable) attributes[i]; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { return (ConstantValue) attributes[i]; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { for (int i = 0; i < attributes.length; i++) { attributes[i].accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { return true; } } return false; } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { return (SourceFile) attributes[i]; } } return null; } }
blob data class, long method t t f data class, long method blob 0 10805 https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java/#L9-L99 1 1375 10805
4546  { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class GridNearAtomicSingleUpdateRequest extends GridNearAtomicAbstractSingleUpdateRequest { /** */ private static final long serialVersionUID = 0L; /** Key to update. */ @GridToStringInclude protected KeyCacheObject key; /** Value to update. */ protected CacheObject val; /** * Empty constructor required by {@link Externalizable}. */ public GridNearAtomicSingleUpdateRequest() { // No-op. } /** * Constructor. * * @param cacheId Cache ID. * @param nodeId Node ID. * @param futId Future ID. * @param topVer Topology version. * @param syncMode Synchronization mode. * @param op Cache update operation. * @param subjId Subject ID. * @param taskNameHash Task name hash code. * @param flags Flags. * @param addDepInfo Deployment info flag. */ GridNearAtomicSingleUpdateRequest( int cacheId, UUID nodeId, long futId, @NotNull AffinityTopologyVersion topVer, CacheWriteSynchronizationMode syncMode, GridCacheOperation op, @Nullable UUID subjId, int taskNameHash, byte flags, boolean addDepInfo ) { super(cacheId, nodeId, futId, topVer, syncMode, op, subjId, taskNameHash, flags, addDepInfo ); } /** {@inheritDoc} */ @Override public int partition() { assert key != null; return key.partition(); } /** * @param key Key to add. * @param val Optional update value. * @param conflictTtl Conflict TTL (optional). * @param conflictExpireTime Conflict expire time (optional). * @param conflictVer Conflict version (optional). */ @Override public void addUpdateEntry(KeyCacheObject key, @Nullable Object val, long conflictTtl, long conflictExpireTime, @Nullable GridCacheVersion conflictVer) { assert op != TRANSFORM; assert val != null || op == DELETE; assert conflictTtl < 0 : conflictTtl; assert conflictExpireTime < 0 : conflictExpireTime; assert conflictVer == null : conflictVer; this.key = key; if (val != null) { assert val instanceof CacheObject : val; this.val = (CacheObject)val; } } /** {@inheritDoc} */ @Override public int size() { assert key != null; return key == null ? 0 : 1; } /** {@inheritDoc} */ @Override public List keys() { return Collections.singletonList(key); } /** {@inheritDoc} */ @Override public KeyCacheObject key(int idx) { assert idx == 0 : idx; return key; } /** {@inheritDoc} */ @Override public List values() { return Collections.singletonList(val); } /** {@inheritDoc} */ @Override public CacheObject value(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Override public EntryProcessor entryProcessor(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public CacheObject writeValue(int idx) { assert idx == 0 : idx; return val; } /** {@inheritDoc} */ @Nullable @Override public List conflictVersions() { return null; } /** {@inheritDoc} */ @Nullable @Override public GridCacheVersion conflictVersion(int idx) { assert idx == 0 : idx; return null; } /** {@inheritDoc} */ @Override public long conflictTtl(int idx) { assert idx == 0 : idx; return CU.TTL_NOT_CHANGED; } /** {@inheritDoc} */ @Override public long conflictExpireTime(int idx) { assert idx == 0 : idx; return CU.EXPIRE_TIME_CALCULATE; } /** {@inheritDoc} */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); GridCacheContext cctx = ctx.cacheContext(cacheId); prepareMarshalCacheObject(key, cctx); if (val != null) prepareMarshalCacheObject(val, cctx); } /** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); GridCacheContext cctx = ctx.cacheContext(cacheId); key.finishUnmarshal(cctx.cacheObjectContext(), ldr); if (val != null) val.finishUnmarshal(cctx.cacheObjectContext(), ldr); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!super.writeTo(buf, writer)) return false; if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 11: if (!writer.writeMessage("key", key)) return false; writer.incrementState(); case 12: if (!writer.writeMessage("val", val)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 11: key = reader.readMessage("key"); if (!reader.isLastRead()) return false; reader.incrementState(); case 12: val = reader.readMessage("val"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridNearAtomicSingleUpdateRequest.class); } /** {@inheritDoc} */ @Override public void cleanup(boolean clearKey) { val = null; if (clearKey) key = null; } /** {@inheritDoc} */ @Override public short directType() { return 125; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 13; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridNearAtomicSingleUpdateRequest.class, this, "parent", super.toString()); } }
blob data class, long method t t f data class, long method blob 0 12082 https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicSingleUpdateRequest.java/#L49-L321 1 4546 12082
263     { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private static class DoubleTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; DoubleTreeWriter(int columnId, TypeDescription schema, StreamFactory writer, boolean nullable) throws IOException { super(columnId, schema, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Datum datum) throws IOException { super.write(datum); if (datum != null && datum.isNotNull()) { double val = datum.asFloat8(); indexStatistics.updateDouble(val); if (createBloomFilter) { bloomFilter.addDouble(val); } utils.writeDouble(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } }
blob long method, data class t t f long method, data class blob 0 2855 https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-storage/tajo-storage-hdfs/src/main/java/org/apache/tajo/storage/thirdparty/orc/WriterImpl.java/#L1041-L1082 1 263 2855
1953     { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class RabbitBusCleaner implements BusCleaner { private final static Logger logger = LoggerFactory.getLogger(RabbitBusCleaner.class); @Override public Map> clean(String entity, boolean isJob) { return clean("http://localhost:15672", "guest", "guest", "/", "xdbus.", entity, isJob); } public Map> clean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { return doClean( adminUri == null ? "http://localhost:15672" : adminUri, user == null ? "guest" : user, pw == null ? "guest" : pw, vhost == null ? "/" : vhost, busPrefix == null ? "xdbus." : busPrefix, entity, isJob); } private Map> doClean(String adminUri, String user, String pw, String vhost, String busPrefix, String entity, boolean isJob) { RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); List removedQueues = isJob ? findJobQueues(adminUri, vhost, busPrefix, entity, restTemplate) : findStreamQueues(adminUri, vhost, busPrefix, entity, restTemplate); ExchangeCandidateCallback callback; if (isJob) { String pattern; if (entity.endsWith("*")) { pattern = entity.substring(0, entity.length() - 1) + "[^.]*"; } else { pattern = entity; } Collection exchangeNames = JobEventsListenerPlugin.getEventListenerChannels(pattern).values(); final Set jobExchanges = new HashSet<>(); for (String exchange : exchangeNames) { jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(exchange)))); } jobExchanges.add(Pattern.compile(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub( JobEventsListenerPlugin.getEventListenerChannelName(pattern))))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { for (Pattern pattern : jobExchanges) { Matcher matcher = pattern.matcher(exchangeName); if (matcher.matches()) { return true; } } return false; } }; } else { final String tapPrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(entity)))); callback = new ExchangeCandidateCallback() { @Override public boolean isCandidate(String exchangeName) { return exchangeName.startsWith(tapPrefix); } }; } List removedExchanges = findExchanges(adminUri, vhost, busPrefix, entity, restTemplate, callback); // Delete the queues in reverse order to enable re-running after a partial success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{stream}") .buildAndExpand(vhost, queueName).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted queue: " + queueName); } } Map> results = new HashMap<>(); if (removedQueues.size() > 0) { results.put("queues", removedQueues); } // Fanout exchanges for taps for (String exchange : removedExchanges) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}") .buildAndExpand(vhost, exchange).encode().toUri(); restTemplate.delete(uri); if (logger.isDebugEnabled()) { logger.debug("deleted exchange: " + exchange); } } if (removedExchanges.size() > 0) { results.put("exchanges", removedExchanges); } return results; } private List findStreamQueues(String adminUri, String vhost, String busPrefix, String stream, RestTemplate restTemplate) { String queueNamePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (queueName.startsWith(queueNamePrefix)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } return removedQueues; } private List findJobQueues(String adminUri, String vhost, String busPrefix, String job, RestTemplate restTemplate) { List removedQueues = new ArrayList<>(); String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job)); String jobRequestsQueuePrefix = adjustPrefix(MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job))); List> queues = listAllQueues(adminUri, vhost, restTemplate); for (Map queue : queues) { String queueName = (String) queue.get("name"); if (job.endsWith("*")) { if (queueName.startsWith(jobQueueName.substring(0, jobQueueName.length() - 1))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } else { if (queueName.equals(jobQueueName)) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } else if (queueName.startsWith(jobRequestsQueuePrefix) && queueName.endsWith(MessageBusSupport.applyRequests(""))) { checkNoConsumers(queueName, queue); removedQueues.add(queueName); } } } return removedQueues; } private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}") .buildAndExpand(vhost).encode().toUri(); @SuppressWarnings("unchecked") List> queues = restTemplate.getForObject(uri, List.class); return queues; } private String adjustPrefix(String prefix) { if (prefix.endsWith("*")) { return prefix.substring(0, prefix.length() - 1); } else { return prefix + BusUtils.GROUP_INDEX_DELIMITER; } } private void checkNoConsumers(String queueName, Map queue) { if (!queue.get("consumers").equals(Integer.valueOf(0))) { throw new RabbitAdminException("Queue " + queueName + " is in use"); } } @SuppressWarnings("unchecked") private List findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); } } else { throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } private interface ExchangeCandidateCallback { boolean isCandidate(String exchangeName); } }
blob long method, data class t t f long method, data class blob 0 12539 https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/integration/bus/rabbit/RabbitBusCleaner.java/#L50-L264 1 1953 12539
2407 {"response": "YES I found bad smells the bad smells are: 1. Data Class"} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } }
blob 1. data class t t f 1. data class blob 0 14389 https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 1 2407 14389
1207 {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); }
long method data class, long method t t t data class   0 10290 https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 1 1207 10290
677                  { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } }
blob long method, data class t t f long method, data class blob 0 6583 https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 1 677 6583
1608      { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class XPathParser { private final Map prefixes = new HashMap(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // for compatibility return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } }
blob Data Class, Long Method t f f Data Class, Long Method blob 0 11455 https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-core/src/main/java/org/apache/tika/sax/xpath/XPathParser.java/#L40-L120 1 1608 11455
774 {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class StreamRecords { /** * Create a new {@link ByteRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteRecord}. */ public static ByteRecord rawBytes(Map raw) { return new ByteMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static ByteBufferRecord rawBuffer(Map raw) { return new ByteBufferMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link ByteBufferRecord} for the given raw field/value pairs. * * @param raw must not be {@literal null}. * @return new instance of {@link ByteBufferRecord}. */ public static StringRecord string(Map raw) { return new StringMapBackedRecord(null, RecordId.autoGenerate(), raw); } /** * Create a new {@link MapRecord} backed by the field/value pairs of the given {@link Map}. * * @param map must not be {@literal null}. * @param type of the stream key. * @param type of the map key. * @param type of the map value. * @return new instance of {@link MapRecord}. */ public static MapRecord mapBacked(Map map) { return new MapBackedRecord<>(null, RecordId.autoGenerate(), map); } /** * Create new {@link ObjectRecord} backed by the given value. * * @param value must not be {@literal null}. * @param the stream key type * @param the value type. * @return new instance of {@link ObjectRecord}. */ public static ObjectRecord objectBacked(V value) { return new ObjectBackedRecord<>(null, RecordId.autoGenerate(), value); } /** * Obtain new instance of {@link RecordBuilder} to fluently create {@link Record records}. * * @return new instance of {@link RecordBuilder}. */ public static RecordBuilder newRecord() { return new RecordBuilder<>(null, RecordId.autoGenerate()); } // Utility constructor private StreamRecords() {} /** * Builder for {@link Record}. * * @param stream keyy type. */ public static class RecordBuilder { private RecordId id; private S stream; RecordBuilder(@Nullable S stream, RecordId recordId) { this.stream = stream; this.id = recordId; } /** * Configure a stream key. * * @param stream the stream key, must not be null. * @param * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder in(STREAM_KEY stream) { Assert.notNull(stream, "Stream key must not be null"); return new RecordBuilder<>(stream, id); } /** * Configure a record Id given a {@link String}. Associates a user-supplied record id instead of using * server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. * @see RecordId */ public RecordBuilder withId(String id) { return withId(RecordId.of(id)); } /** * Configure a {@link RecordId}. Associates a user-supplied record id instead of using server-generated record Id's. * * @param id the record id. * @return {@literal this} {@link RecordBuilder}. */ public RecordBuilder withId(RecordId id) { Assert.notNull(id, "RecordId must not be null"); this.id = id; return this; } /** * Create a {@link MapRecord}. * * @param map * @param * @param * @return new instance of {@link MapRecord}. */ public MapRecord ofMap(Map map) { return new MapBackedRecord<>(stream, id, map); } /** * Create a {@link StringRecord}. * * @param map * @return new instance of {@link StringRecord}. * @see MapRecord */ public StringRecord ofStrings(Map map) { return new StringMapBackedRecord(ObjectUtils.nullSafeToString(stream), id, map); } /** * Create an {@link ObjectRecord}. * * @param value * @param * @return new instance of {@link ObjectRecord}. */ public ObjectRecord ofObject(V value) { return new ObjectBackedRecord<>(stream, id, value); } /** * @param value * @return new instance of {@link ByteRecord}. */ public ByteRecord ofBytes(Map value) { // todo auto conversion of known values return new ByteMapBackedRecord((byte[]) stream, id, value); } /** * @param value * @return new instance of {@link ByteBufferRecord}. */ public ByteBufferRecord ofBuffer(Map value) { ByteBuffer streamKey; if (stream instanceof ByteBuffer) { streamKey = (ByteBuffer) stream; } else if (stream instanceof String) { streamKey = ByteUtils.getByteBuffer((String) stream); } else if (stream instanceof byte[]) { streamKey = ByteBuffer.wrap((byte[]) stream); } else { throw new IllegalArgumentException(String.format("Stream key %s cannot be converted to byte buffer.", stream)); } return new ByteBufferMapBackedRecord(streamKey, id, value); } } /** * Default implementation of {@link MapRecord}. * * @param * @param * @param */ static class MapBackedRecord implements MapRecord { private @Nullable S stream; private RecordId recordId; private final Map kvMap; MapBackedRecord(@Nullable S stream, RecordId recordId, Map kvMap) { this.stream = stream; this.recordId = recordId; this.kvMap = kvMap; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public Iterator> iterator() { return kvMap.entrySet().iterator(); } @Override public Map getValue() { return kvMap; } @Override public MapRecord withId(RecordId id) { return new MapBackedRecord<>(stream, id, this.kvMap); } @Override public MapRecord withStreamKey(S1 key) { return new MapBackedRecord<>(key, recordId, this.kvMap); } @Override public String toString() { return "MapBackedRecord{" + "recordId=" + recordId + ", kvMap=" + kvMap + '}'; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!ClassUtils.isAssignable(MapBackedRecord.class, o.getClass())) { return false; } MapBackedRecord that = (MapBackedRecord) o; if (!ObjectUtils.nullSafeEquals(this.stream, that.stream)) { return false; } if (!ObjectUtils.nullSafeEquals(this.recordId, that.recordId)) { return false; } return ObjectUtils.nullSafeEquals(this.kvMap, that.kvMap); } @Override public int hashCode() { int result = stream != null ? stream.hashCode() : 0; result = 31 * result + recordId.hashCode(); result = 31 * result + kvMap.hashCode(); return result; } } /** * Default implementation of {@link ByteRecord}. */ static class ByteMapBackedRecord extends MapBackedRecord implements ByteRecord { ByteMapBackedRecord(byte[] stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteMapBackedRecord withStreamKey(byte[] key) { return new ByteMapBackedRecord(key, getId(), getValue()); } @Override public ByteMapBackedRecord withId(RecordId id) { return new ByteMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ByteBufferRecord}. */ static class ByteBufferMapBackedRecord extends MapBackedRecord implements ByteBufferRecord { ByteBufferMapBackedRecord(ByteBuffer stream, RecordId recordId, Map map) { super(stream, recordId, map); } @Override public ByteBufferMapBackedRecord withStreamKey(ByteBuffer key) { return new ByteBufferMapBackedRecord(key, getId(), getValue()); } @Override public ByteBufferMapBackedRecord withId(RecordId id) { return new ByteBufferMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of StringRecord. */ static class StringMapBackedRecord extends MapBackedRecord implements StringRecord { StringMapBackedRecord(String stream, RecordId recordId, Map stringStringMap) { super(stream, recordId, stringStringMap); } @Override public StringRecord withStreamKey(String key) { return new StringMapBackedRecord(key, getId(), getValue()); } @Override public StringMapBackedRecord withId(RecordId id) { return new StringMapBackedRecord(getStream(), id, getValue()); } } /** * Default implementation of {@link ObjectRecord}. * * @param * @param */ @EqualsAndHashCode static class ObjectBackedRecord implements ObjectRecord { private @Nullable S stream; private RecordId recordId; private final V value; ObjectBackedRecord(@Nullable S stream, RecordId recordId, V value) { this.stream = stream; this.recordId = recordId; this.value = value; } @Nullable @Override public S getStream() { return stream; } @Nullable @Override public RecordId getId() { return recordId; } @Override public V getValue() { return value; } @Override public ObjectRecord withId(RecordId id) { return new ObjectBackedRecord<>(stream, id, value); } @Override public ObjectRecord withStreamKey(SK key) { return new ObjectBackedRecord<>(key, recordId, value); } @Override public String toString() { return "ObjectBackedRecord{" + "recordId=" + recordId + ", value=" + value + '}'; } } }
blob data class t t f data class blob 0 7350 https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/stream/StreamRecords.java/#L37-L435 1 774 7350
1964 { "output": "YES I found bad smells the bad smells are: 1. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } }
blob 1. data class t t f 1. data class blob 0 12590 https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 1 1964 12590
1955  { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
public class CtagsReader { /** * Matches the Unicode word that occurs last in a string, ignoring any * trailing whitespace or non-word characters, and makes it accessible as * the first capture, {@code mtch.groups(1)}: * * {@code * (?U)(\w+)[\W\s]*$ * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern LAST_UWORD = Pattern.compile( "(?U)(\\w+)[\\W\\s]*$"); /** * Matches a Unicode word character: * * {@code * (?U)\w * } * * (Edit above and paste below [in NetBeans] for easy String escaping.) */ private static final Pattern WORD_CHAR = Pattern.compile("(?U)\\w"); private static final Logger LOGGER = LoggerFactory.getLogger( CtagsReader.class); /** A value indicating empty method body in tags, so skip it */ private static final int MIN_METHOD_LINE_LENGTH = 6; /** * 96 is used by universal ctags for some lines, but it's too low, * OpenGrok can theoretically handle 50000 with 8G heap. Also this might * break scopes functionality, if set too low. */ private static final int MAX_METHOD_LINE_LENGTH = 1030; private static final int MAX_CUT_LENGTH = 2000; /** * E.g. krb5 src/kdc/kdc_authdata.c has a signature for handle_authdata() * split across twelve lines, so use double that number. */ private static final int MAX_CUT_LINES = 24; private final EnumMap fields = new EnumMap<>( tagFields.class); private final Definitions defs = new Definitions(); private Supplier splitterSupplier; private boolean triedSplitterSupplier; private SourceSplitter splitter; private long cutCacheKey; private String cutCacheValue; private int tabSize; /** * This should mimic * https://github.com/universal-ctags/ctags/blob/master/docs/format.rst or * http://ctags.sourceforge.net/FORMAT (for backwards compatibility). * Uncomment only those that are used ... (to avoid populating the hashmap * for every record). */ public enum tagFields { // ARITY("arity"), CLASS("class"), // INHERIT("inherit"), //this is not defined in above format docs, but both universal and exuberant ctags use it // INTERFACE("interface"), //this is not defined in above format docs, but both universal and exuberant ctags use it // ENUM("enum"), // FILE("file"), // FUNCTION("function"), // KIND("kind"), LINE("line"), // NAMESPACE("namespace"), //this is not defined in above format docs, but both universal and exuberant ctags use it // PROGRAM("program"), //this is not defined in above format docs, but both universal and exuberant ctags use it SIGNATURE("signature"); // STRUCT("struct"), // TYPEREF("typeref"), // UNION("union"); //NOTE: if you edit above, always consult below charCmpEndOffset private final String name; /** * Sets {@code this.name} to {@code name}. * @param name the assignment value */ tagFields(String name) { this.name = name; } /** * N.b. make this MAX. 8 chars! (backwards compat to DOS/Win). * 1 - means only 2 first chars are compared. * This is very important, we only compare that amount of chars from * field types with input to save time. This number has to be long * enough to get rid of disambiguation. * TODO: * NOTE this is a big tradeoff in terms of input data, e.g. field * "find" will be considered "file" and overwrite the value, so if * ctags will send us buggy input. We will output buggy data TOO! NO * VALIDATION happens of input - but then we gain LOTS of speed, due to * not comparing the same field names again and again fully. */ public static int charCmpEndOffset = 0; /** * Quickly get if the field name matches allowed/consumed ones * @param fullName the name to look up * @return a defined value, or null if unmatched */ public static CtagsReader.tagFields quickValueOf(String fullName) { int i; boolean match; for (tagFields x : tagFields.values()) { match = true; for (i = 0; i <= charCmpEndOffset; i++) { if (x.name.charAt(i) != fullName.charAt(i)) { match = false; break; } } if (match) { return x; } } return null; } } public int getTabSize() { return tabSize; } public void setTabSize(int tabSize) { this.tabSize = tabSize; } /** * Gets the instance's definitions. * @return a defined instance */ public Definitions getDefinitions() { return defs; } /** * Sets the supplier of a {@link SourceSplitter} to use when ctags pattern * is insufficient, and the reader could use the source data. * * N.b. because an I/O exception can occur, the supplier may return * {@code null}, which the {@link CtagsReader} handles. * @param obj defined instance or {@code null} */ public void setSplitterSupplier(Supplier obj) { splitter = null; triedSplitterSupplier = false; splitterSupplier = obj; } /** * Reads a line into the instance's definitions. * @param tagLine a defined line or null to no-op */ public void readLine(String tagLine) { if (tagLine == null) { return; } int p = tagLine.indexOf('\t'); if (p <= 0) { //log.fine("SKIPPING LINE - NO TAB"); return; } String def = tagLine.substring(0, p); int mstart = tagLine.indexOf('\t', p + 1); String kind = null; int lp = tagLine.length(); while ((p = tagLine.lastIndexOf('\t', lp - 1)) > 0) { //log.fine(" p = " + p + " lp = " + lp); String fld = tagLine.substring(p + 1, lp); //log.fine("FIELD===" + fld); lp = p; int sep = fld.indexOf(':'); if (sep != -1) { tagFields pos = tagFields.quickValueOf(fld); if (pos != null) { String val = fld.substring(sep + 1); fields.put(pos, val); } else { //unknown field name //don't log on purpose, since we don't consume all possible // fields, so just ignore this error for now // LOGGER.log(Level.WARNING, "Unknown field name found: {0}", // fld.substring(0, sep - 1)); } } else { //TODO no separator, assume this is the kind kind = fld; break; } } String lnum = fields.get(tagFields.LINE); String signature = fields.get(tagFields.SIGNATURE); String classInher = fields.get(tagFields.CLASS); final String whole; final String match; int mlength = p - mstart; if ((p > 0) && (mlength > MIN_METHOD_LINE_LENGTH)) { whole = cutPattern(tagLine, mstart, p); if (mlength < MAX_METHOD_LINE_LENGTH) { match = whole.replaceAll("[ \t]+", " "); //TODO per format we should also recognize \r and \n } else { LOGGER.log(Level.FINEST, "Ctags: stripping method" + " body for def {0} line {1}(scopes/highlight" + " might break)", new Object[]{def, lnum}); match = whole.substring(0, MAX_METHOD_LINE_LENGTH).replaceAll( "[ \t]+", " "); } } else { //tag is wrong format; cannot extract tagaddress from it; skip return; } // Bug #809: Keep track of which symbols have already been // seen to prevent duplicating them in memory. final String type = classInher == null ? kind : kind + " in " + classInher; int lineno; try { lineno = Integer.parseUnsignedInt(lnum); } catch (NumberFormatException e) { lineno = 0; LOGGER.log(Level.WARNING, "CTags line number parsing problem(but" + " I will continue with line # 0) for symbol {0}", def); } CpatIndex cidx = bestIndexOfTag(lineno, whole, def); addTag(defs, cidx.lineno, def, type, match, classInher, signature, cidx.lineStart, cidx.lineEnd); String[] args; if (signature != null && !signature.equals("()") && !signature.startsWith("() ") && (args = splitSignature(signature)) != null) { for (String arg : args) { //TODO this algorithm assumes that data types occur to // the left of the argument name, so it will not // work for languages like rust, kotlin, etc. which // place the data type to the right of the argument name. // Need an attribute from ctags to indicate data type // location. // ------------------------------------------------------------ // When no assignment of default values, // expecting: , or // // When default value assignment applied to parameter, // expecting: = or // = // (Note whitespace content made irrelevant) // Need to ditch the default assignment value // so that the extraction loop below will work. // This assumes all languages use '=' to assign value. if (arg.contains("=")) { String[] a = arg.split("="); arg = a[0]; // throws away assigned value } arg = arg.trim(); if (arg.length() < 1) { continue; } cidx = bestIndexOfArg(lineno, whole, arg); String name = null; Matcher mname = LAST_UWORD.matcher(arg); if (mname.find()) { name = mname.group(1); } else if (arg.equals("...")) { name = arg; } if (name != null) { addTag(defs, cidx.lineno, name, "argument", def.trim() + signature.trim(), null, signature, cidx.lineStart, cidx.lineEnd); } else { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Not matched arg:{0}|sig:{1}", new Object[]{arg, signature}); } } } } // log.fine("Read = " + def + " : " + lnum + " = " + kind + " IS " + // inher + " M " + match); fields.clear(); } /** * Cuts the ctags TAG FILE FORMAT search pattern from the specified * {@code tagLine} between the specified tab positions, and un-escapes * {@code \\} and {@code \/}. * @return a defined string */ private static String cutPattern(String tagLine, int startTab, int endTab) { // Three lead character represents "\t/^". String cut = tagLine.substring(startTab + 3, endTab); /** * Formerly this class cut four characters from the end, but my testing * revealed a bug for short lines in files with macOS endings (e.g. * cyrus-sasl mac/libdes/src/des_enc.c) where the pattern-ending $ is * not present. Now, inspect the end of the pattern to determine the * true cut -- which is appropriate for all content anyway. */ if (cut.endsWith("$/;\"")) { cut = cut.substring(0, cut.length() - 4); } else if (cut.endsWith("/;\"")) { cut = cut.substring(0, cut.length() - 3); } else { /** * The former logic did the following without the inspections above. * Leaving this here as a fallback. */ cut = cut.substring(0, cut.length() - 4); } return cut.replace("\\\\", "\\").replace("\\/", "/"); } /** * Adds a tag to a {@code Definitions} instance. */ private void addTag(Definitions defs, int lineno, String symbol, String type, String text, String namespace, String signature, int lineStart, int lineEnd) { // The strings are frequently repeated (a symbol can be used in // multiple definitions, multiple definitions can have the same type, // one line can contain multiple definitions). Intern them to minimize // the space consumed by them (see bug #809). defs.addTag(lineno, symbol.trim().intern(), type.trim().intern(), text.trim().intern(), namespace == null ? null : namespace.trim().intern(), signature, lineStart, lineEnd); } /** * Searches for the index of the best match of {@code str} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax. * @return a defined instance */ private CpatIndex bestIndexOfTag(int lineno, String whole, String str) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } String origWhole = whole; int t = tabSize; int s, e; int woff = strictIndexOf(whole, str); if (woff < 0) { /** * When a splitter is available, search the entire line. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, 1); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { whole = cut; woff = strictIndexOf(whole, str); } if (woff < 0) { /** At this point, do a lax search of the substring. */ woff = whole.indexOf(str); } } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + str.length(), t); return new CpatIndex(lineno, s, e); } /** * When ctags has truncated a pattern, or when it spans multiple lines, * then `str' might not be found in `whole'. In that case, return an * imprecise index for the last character as the best we can do. */ s = ExpandTabsReader.translate(origWhole, origWhole.length() - 1, t); e = ExpandTabsReader.translate(origWhole, origWhole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches for the index of the best match of {@code arg} in {@code whole} * in a multi-stage algorithm that first starts strictly to disfavor * abutting words and then relaxes -- and also works around ctags's possibly * having returned a partial line or only one line of a multi-line language * syntax or where ctags has transformed syntax. * * E.g., the true source might read {@code const fru_regdef_t *d} with the * ctags signature reading {@code const fru_regdef_t * d} * @return a defined instance */ private CpatIndex bestIndexOfArg(int lineno, String whole, String arg) { if (whole.length() < 1) { return new CpatIndex(lineno, 0, 1, true); } int t = tabSize; int s, e; // First search arg as-is in the current `whole' -- strict then lax. int woff = strictIndexOf(whole, arg); if (woff < 0) { woff = whole.indexOf(arg); } if (woff >= 0) { s = ExpandTabsReader.translate(whole, woff, t); e = ExpandTabsReader.translate(whole, woff + arg.length(), t); return new CpatIndex(lineno, s, e); } // Build a pattern from `arg' with looseness around whitespace. StringBuilder bld = new StringBuilder(); int spos = 0; boolean lastWhitespace = false; boolean firstNonWhitespace = false; for (int i = 0; i < arg.length(); ++i) { char c = arg.charAt(i); if (Character.isWhitespace(c)) { if (!firstNonWhitespace) { ++spos; } else if (!lastWhitespace) { lastWhitespace = true; if (spos < i) { bld.append(Pattern.quote(arg.substring(spos, i))); } // m`\s*` bld.append("\\s*"); } } else { firstNonWhitespace = true; if (lastWhitespace) { lastWhitespace = false; spos = i; } } } if (spos < arg.length()) { bld.append(Pattern.quote(arg.substring(spos))); } if (bld.length() < 1) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Odd arg:{0}|versus:{1}|line {2}", new Object[]{arg, whole, lineno}); } /** * When no fuzzy match can be generated, return an imprecise index * for the first character as the best we can do. */ return new CpatIndex(lineno, 0, 1, true); } Pattern argpat = Pattern.compile(bld.toString()); PatResult pr = bestMatch(whole, arg, argpat); if (pr.start >= 0) { s = ExpandTabsReader.translate(whole, pr.start, t); e = ExpandTabsReader.translate(whole, pr.end, t); return new CpatIndex(lineno, s, e); } /** * When a splitter is available, search the next several lines. * (N.b. use 0-offset vs ctags's 1-offset.) */ String cut = trySplitterCut(lineno - 1, MAX_CUT_LINES); if (cut == null || !cut.startsWith(whole)) { if (LOGGER.isLoggable(Level.FINE)) { String readablecut = cut != null ? cut : "null\n"; LOGGER.log(Level.FINE, "Bad cut:{0}|versus:{1}|line {2}", new Object[]{readablecut, whole, lineno}); } } else { pr = bestMatch(cut, arg, argpat); if (pr.start >= 0) { return bestLineOfMatch(lineno, pr, cut); } } /** * When no match is found, return an imprecise index for the last * character as the best we can do. */ s = ExpandTabsReader.translate(whole, whole.length() - 1, t); e = ExpandTabsReader.translate(whole, whole.length(), t); return new CpatIndex(lineno, s, e, true); } /** * Searches strictly then laxly. */ private PatResult bestMatch(String whole, String arg, Pattern argpat) { PatResult m = strictMatch(whole, arg, argpat); if (m.start >= 0) { return m; } Matcher marg = argpat.matcher(whole); if (marg.find()) { return new PatResult(marg.start(), marg.end(), marg.group()); } // Return m, which was invalid if we got to here. return m; } /** * Like {@link String#indexOf(java.lang.String)} but strict that a * {@code substr} starting with a word character cannot abut another word * character on its left and likewise on the right for a {@code substr} * ending with a word character. */ private int strictIndexOf(String whole, String substr) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); int spos = 0; do { int woff = whole.indexOf(substr, spos); if (woff < 0) { return -1; } spos = woff + 1; String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && woff > 0) { onechar = String.valueOf(whole.charAt(woff - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && woff + substr.length() < whole.length()) { onechar = String.valueOf(whole.charAt(woff + substr.length())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return woff; } while (spos < whole.length()); return -1; } /** * Like {@link #strictIndexOf(java.lang.String, java.lang.String)} but using * a pattern. */ private PatResult strictMatch(String whole, String substr, Pattern pat) { boolean strictLeft = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(0))).matches(); boolean strictRight = substr.length() > 0 && WORD_CHAR.matcher( String.valueOf(substr.charAt(substr.length() - 1))).matches(); Matcher m = pat.matcher(whole); while (m.find()) { String onechar; /** * Reject if the previous character is a word character, as that * would not accord with a clean symbol break */ if (strictLeft && m.start() > 0) { onechar = String.valueOf(whole.charAt(m.start() - 1)); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } /** * Reject if the following character is a word character, as that * would not accord with a clean symbol break */ if (strictRight && m.end() < whole.length()) { onechar = String.valueOf(whole.charAt(m.end())); if (WORD_CHAR.matcher(onechar).matches()) { continue; } } return new PatResult(m.start(), m.end(), m.group()); } return new PatResult(-1, -1, null); } /** * Finds the line with the longest content from {@code midx}. * * The {@link Definitions} tag model is based on a match within a line. * "signature" fields, however, can be condensed from multiple lines; and a * fuzzy match can therefore span multiple lines. */ private CpatIndex bestLineOfMatch(int lineno, PatResult pr, String cut) { // (N.b. use 0-offset vs ctags's 1-offset.) int lpos = splitter.getPosition(lineno - 1); int mpos = lpos + pr.start; int moff = splitter.findLineOffset(mpos); int zpos = lpos + pr.end - 1; int zoff = splitter.findLineOffset(zpos); int t = tabSize; int resoff = moff; int contentLength = 0; /** * Initialize the following just to silence warnings but with values * that will be detected as "bad fuzzy" later. */ String whole = ""; int s = 0; int e = 1; /** * Iterate to determine the length of the portion of `midx' that * is contained within each line. */ for (int ioff = moff; ioff <= zoff; ++ioff) { String iwhole = splitter.getLine(ioff); int ioffpos = splitter.getPosition(ioff); int iendpos = ioffpos + iwhole.length(); int i_s = pr.start + lpos < ioffpos ? ioffpos : pr.start + lpos; int i_e = pr.end + lpos > iendpos ? iendpos : pr.end + lpos; if (i_e - i_s > contentLength) { contentLength = i_e - i_s; resoff = ioff; whole = iwhole; // (The following are not yet adjusted for tabs.) s = i_s - ioffpos; e = i_e - ioffpos; } } if (s >= 0 && s < whole.length() && e >= 0 && e <= whole.length()) { s = ExpandTabsReader.translate(whole, s, t); e = ExpandTabsReader.translate(whole, e, t); // (N.b. use ctags's 1-offset.) return new CpatIndex(resoff + 1, s, e); } /** * This should not happen -- but if it does, log it and return an * imprecise index for the first character as the best we can do. */ if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Bad fuzzy:{0}|versus:{1}|line {2} pos {3}-{4}|{5}|", new Object[]{pr.capture, cut, lineno, s, e, whole}); } return new CpatIndex(lineno, 0, 1, true); } /** * TODO if some languages use different character for separating arguments, * below needs to be adjusted. * @return a defined instance or null */ private static String[] splitSignature(String signature) { int off0 = 0; int offz = signature.length(); int soff = off0; int eoff = offz; if (soff >= eoff) { return null; } // Trim outer punctuation if it exists. while (soff < signature.length() && (signature.charAt(soff) == '(' || signature.charAt(soff) == '{')) { ++soff; } while (eoff - 1 > soff && (signature.charAt(eoff - 1) == ')' || signature.charAt(eoff - 1) == '}')) { --eoff; } if (soff > off0 || eoff < offz) { signature = signature.substring(soff, eoff); } return signature.split(","); } /** * Tries to cut lines from a splitter provided by {@code splitterSupplier}. * @return a defined instance if a successful cut is made or else * {@code null} */ private String trySplitterCut(int lineOffset, int maxLines) { if (splitter == null) { if (splitterSupplier == null || triedSplitterSupplier) { return null; } triedSplitterSupplier = true; splitter = splitterSupplier.get(); if (splitter == null) { return null; } } long newCutCacheKey = ((long)lineOffset << 32) | maxLines; if (cutCacheKey == newCutCacheKey) { return cutCacheValue; } StringBuilder cutbld = new StringBuilder(); for (int i = lineOffset; i < lineOffset + maxLines && i < splitter.count() && cutbld.length() < MAX_CUT_LENGTH; ++i) { cutbld.append(splitter.getLine(i)); } if (cutbld.length() > MAX_CUT_LENGTH) { cutbld.setLength(MAX_CUT_LENGTH); } cutCacheValue = cutbld.toString(); cutCacheKey = newCutCacheKey; return cutCacheValue; } /** * Represents an index into ctags pattern entries. */ private static class CpatIndex { public final int lineno; public final int lineStart; public final int lineEnd; public final boolean imprecise; CpatIndex(int lineno, int lineStart, int lineEnd) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = false; } CpatIndex(int lineno, int lineStart, int lineEnd, boolean imprecise) { this.lineno = lineno; this.lineStart = lineStart; this.lineEnd = lineEnd; this.imprecise = imprecise; } } /** * Represents a result from a pattern match -- valid if lineStart is greater * than or equal to zero. */ private static class PatResult { public final int start; public final int end; public final String capture; PatResult(int start, int end, String capture) { this.start = start; this.end = end; this.capture = capture; } } }
blob long method, data class t t f long method, data class blob 0 12554 https://github.com/oracle/opengrok/blob/bd2770a04a3eda7af19fae482d880d56cce0eeb9/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CtagsReader.java/#L39-L829 1 1955 12554
1188 { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
@Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; }
long method long method, data class t t t  data class   0 10247 https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 1 1188 10247
3373 { "input_code": "public class User {\n private String name;\n private int age;\n\n public User(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n}", "detected_bad_smells": "YES I found bad smells\nthe bad smells are: 1. Data Class" } The list below presents common code smells (aka bad
smells) I need to check if the Java code provided at the
end of the input contains at least one of them.
* Blob
* Data Class
* Feature Envy
* Long Method
Could you please identify which smells occur in the
following code? However, do not describe the smells, just
list them.
Please start your answer with “YES I found bad smells”
when you find any bad smell. Otherwise, start your answer
with “NO, I did not find any bad smell”.
When you start to list the detected bad smells, always
put in your answer “the bad smells are:” amongst the text
your answer and always separate it in this format: 1. Long
method, 2.Feature envy:
None
blob yes i found bad smellsthe bad smells are: 1. data class t t f yes i found bad smellsthe bad smells are: 1. data class blob 0 6419 https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-stubs/src/main/java/org/apache/airavata/registry/api/RegistryService.java/#L139622-L139692 1 3373 6419

(593 rows)